Variable variables in Matlab

牧云@^-^@ 提交于 2019-12-11 05:39:48

问题


I have 30 txt files with data And I want to create on the fly vectors from that files with the name of "file name"

pathforindependents = 'C:\MatLab\independent\'

independents = dir(fullfile(pathforindependents,'ind*.txt'))              

for i = 1:length(independents)

    filename = independents(i).name;
    r=regexp(filename,'\.','split');
    qnumber = r(2)
    qtitle=r(3)

    qpath = strcat(pathforindependents,filename)
    qdata = load(qpath)

    mtrxPrefix = 'mtrx_';

    v = strcat(mtrxPrefix,qtitle);

    eval(???????????????????????)

end

But I dont know how can I do it. No matter what I try Matlab gives me "Undefined function 'eval' for input arguments of type 'cell'." Error?

My data file structure is like

ind.01.AGE.txt

0
1
0
0
0
1
1
0
1
...

At the end I want to reach this

mtrx_AGE =
0
1
0
0
0
1
1
0
1
...

How can I do it ? Thank you.


回答1:


To put the variables in the base workspace, use assignin:

 assignin('base', v, qdata);

As you can see in the assignin documentation, for certain assignment cases you may want to use evalin.




回答2:


you can use fields within structures with sprintf to name variables on the fly:

for i = 1:100
   my_struct.(sprintf('A%s%i','filename',i)) = i^2
end

would make

my_struct.Afilename1 = 1
my_struct.Afilename2 = 4
my_struct.Afilename3 = 9



回答3:


Read Mathworks TechNote 1103 on why you should avoid using EVAL the way you do. Alternatives include cell arrays or structures.



来源:https://stackoverflow.com/questions/11097738/variable-variables-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!