问题
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