简体   繁体   English

在Matlab中从结构创建变量

[英]creating variables from structures in matlab

I have the following example which expresses the type of problem that I'm trying to solve: 我有以下示例表示要解决的问题类型:

clear all
textdata = {'DateTime','St','uSt','Ln','W'};
data = rand(365,4);
Final = struct('data',data,'textdata',{textdata})
clear textdata data

From this, Final.data contains values which correspond to the headings in Final.textdata excluding the first ('DateTime') thus Final.data(:,1) corresponds to the heading 'St'... and so on. 由此,Final.data包含与Final.textdata中的标题相对应的值,但不包括第一个('DateTime'),因此Final.data(:,1)对应于标题'St'...,依此类推。 What I'm trying to do is to create a variable in the workspace for each of these vectors. 我想做的是在工作空间中为每个向量创建一个变量。 So, I would have a variable for St, uSt, Ln, and W in the workspace with the corresponding values given in Final.data. 因此,我将在工作区中使用St,uSt,Ln和W的变量,并在Final.data中给出相应的值。

How could this be done? 怎么办呢?

Will this solve your problem: 这可以解决您的问题:

    for ii=2:length( textdata )
      assignin('base',Final.textdata{ii},Final.data(:,ii-1));
    end

Let me know if I misunderstood. 让我知道我是否误会了。

The direct answer to your question is to use the assignin function, like so (edit: just like macduff suggested 10 minutes ago): 您问题的直接答案是使用assignin函数,如下所示(编辑:就像10分钟前建议的macduff一样):

%Starting with a Final structure containing the data, like this
Final.textdata = {'DateTime','St','uSt','Ln','W'};
Final.data = rand(365,4);

for ix = 1:4
    assignin('base',Final.textdata{ix+1}, Final.data(:,ix));
end

However, I strongly discourage using dynamic variable names to encode data like this. 但是,我强烈不鼓励使用动态变量名称对这样的数据进行编码。 Code that starts this way usually ends up as spaghetti code full of long string concatenations and eval statements. 以这种方式开始的代码通常以充满长字符串连接和eval语句的意大利面条代码结尾。 Better is to use a structure, like this 更好的是使用这样的结构

for ix = 1:4
    dataValues(Final.textdata{ix+1}) = Final.data(:,ix);
end

Or, to get the same result in a single line: 或者,要在一行中获得相同的结果:

dataValues = cell2struct(num2cell(Final.data,1), Final.textdata(2:end),2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM