Creating variable name using sprintf and field of a structure
조회 수: 47 (최근 30일)
이전 댓글 표시
Hi there,
Lets say that from a previous script I have variables with sequential names for date and hour on my workspace: Cs20140312_1623, Cs20140312_1723.
Now I want to perform a series of operations without having to write the variable names manually for every loop, I just want to have a for loop for my filecounter and execute the commands for Cs, Ts for every file.
The date and time that i used to create the names were stored inside the structure myVar, in the field datehour. So I do this:
for filecounter=1:length(FileList)
k=myVar(filecounter).datehour
formatSpec='Cs%d'
Cs=sprintf(formatSpec,k)
% other commands that now will use Cs , Cs will have the values of the respective Csdatehour %
end
But the sprintf call instead of giving ex. Cs20140312_1623, returns Cs50Cs48Cs49Cs52Cs48Cs51Cs49Cs50Cs95Cs49Cs54Cs50Cs51.
This might have sth to do with how the function handles strings? but how to fix that?
Thanx!! Stelina
댓글 수: 1
채택된 답변
Stephen23
2014년 9월 16일
Do not create or use variable names dynamically like this. Use a cell array or structure instead:
댓글 수: 0
추가 답변 (3개)
Image Analyst
2014년 9월 16일
I don't think this is advisable at all - having variables that have names derived from some dynamic process like time or loop index or whatever. It seems like what's discussed and advised against in the FAQ http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F I'd use an array instead.
댓글 수: 0
Iain
2014년 9월 16일
I agree with the advice to NOT name dynamically name variables in a loop. It more often leads to pain than not.
You would be better with a couple of vectors/matrices/cell arrays. One for the date & time and one for the actual data.
I generally avoid sprintf type commands, I find it logically easier to deal with concatenation:
Cs = ['Cs' datestr(k, 'yyyymmdd_HHMM')];
The function "eval" lets you execute code that's dynamically generated, so:
eval(['current = ' Cs ';'])
would be the rest of what you need.
댓글 수: 0
Adam Cutbill
2014년 9월 16일
편집: Adam Cutbill
2014년 9월 16일
I would save the workspace of your old script then load it in your new script. Use the "fieldnames" function to get the names of fields on your loaded object. You can loop using that. For example:
w=load('mymat.mat');
names=fieldnames(w);
names will contain the names of your variables. You may use
for i=1:size(names,1)
mystuff=getfield(w,names{i})
end
after that to access the individual variables in a loop without explicitly writing the names.
In other words, don't use sprintf or eval for this.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!