trouble with the eval function and cell

조회 수: 11 (최근 30일)
Alex R. Crowan
Alex R. Crowan 2012년 1월 20일
편집: per isakson 2017년 2월 16일
Hi guys,
AIM OF FUNCTION
First I need to read out ~100 .mat files with preprocessed data, each containing around 50 variables, a wild mixture of matrices, stings and structs. No problem so far. I then want to store all variables from a file in a cell array.
Example:
load processeddata3.mat
varList = who;
for i=1:+1:size(varList,1)
s = ['data{ex.no,1}.' varList(i) ' = ' varList(i)]
eval(s)
end
where data is the name of the cell array I wish to create, ex.no is the interal number of a dataset.
The string looks like that:
s = 'data{ex.no}.' 'AfterSpikes' ' = ' 'AfterSpikes'
If I type it in by hand it works perferctly, eval gives the error message
??? Undefined function or method 'eval' for input arguments of type 'cell'.
Any idea how to solve this, or an idea for a workaround? Help would really be appreciated.
Thanks, Alex

답변 (2개)

Andrew Newell
Andrew Newell 2012년 1월 20일
Avoid eval - use dynamic field names:
data{ex.no,1}.(varList{i}) = varList{i};
See "Generate Field Names from Variables" in Structures.
A simpler approach is to use
s = load('processeddata3.mat');
EDIT: Modified in view of Walter's comment and discussion below
  댓글 수: 2
Alex R. Crowan
Alex R. Crowan 2012년 1월 21일
편집: per isakson 2017년 2월 16일
Thanks, this is a good tip and I will keep it in mind for the next bit of code I have to write, looks neater than what I did so far for data organisation. Didn't know that worked for structs, and now I wonder what cells are good for, anyway? I hate the curly brackets
Unfortunately, it doesn't quite solve my problem.
The dynamic field name assignment works nice, but the the second part, ' = varList(i);', just assigns the string from varList to the new variable, and not the variable of that name, which was the aim in the first place.
data{ex.no,1}.(varList(i)) = eval(varList(i));
doesn't work either, because my datasets contain cells, too... Unless there is some other trick I'll probably have to put in the 50 variable names myself, could be worse.
Thanks for the answer and have a nice weekend!
Andrew Newell
Andrew Newell 2012년 1월 21일
편집: per isakson 2017년 2월 16일
Oh! You can do that in a single command:
S = load('processeddata3.mat');
As for cells, one nice use for them is to store an array of strings of different lengths - and see also varargin.

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2012년 1월 21일
varList{i} not varList(i)

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by