Hello there,
maybe it's a dumb question, but how do I iterate through alphabetical names? Assuming I have matrices A to D, then how can I use those names in a loop?
My approach would be to create a string
names='ABCD'
and loop through those in a loop
for i=0:4
names(i)
end for
But how can I use this for example for the following operation?
boxplot(A(:))
If I simply use
names='ABCD';
for i=0:4
boxplot(name(i)(:))
end for
Then it doesn't work, of course. strcat does not do the job either.
I hope someone has an idea :)
Cheers

 채택된 답변

Star Strider
Star Strider 2014년 5월 22일

0 개 추천

Not dumb at all.
You need to use the eval function in your loop:
A = rand(2,10);
B = rand(3,10);
C = rand(4,10);
D = rand(5,10);
names = 'ABCD';
for k1 = 1:length(names)
figure(k1)
boxplot(eval(names(k1)))
end

추가 답변 (2개)

Marc
Marc 2014년 5월 22일

0 개 추천

That's great, thank you!
Marc
Marc 2014년 5월 22일

0 개 추천

Okay one more question ... how can I access a variable using a predefined name vector?
for i=1:length(models)
fprintf('\t Open %s\n', models{i})
eval(models(i))=xlsread(strcat(path,'\',eval(models(i)),'_PER.xlsx'));
end
Eval does not do the job here ?

댓글 수: 4

If you already have a predefined variable name, simply use it:
for i=1:length(models)
fprintf('\t Open %s\n', models{i})
models(i)=xlsread(strcat(path,'\',eval(models(i)),'_PER.xlsx'));
end
However you will probably need to add dimensions to it to put the xlsread data into it:
for i=1:length(models)
fprintf('\t Open %s\n', models{i})
models(i,:,:)=xlsread(strcat(path,'\',eval(models(i)),'_PER.xlsx'));
end
Just guessing here, since I have no idea what ‘models’ is, what it contains, or that the various xls arrays are the same size (although I assume here that they are).
Marc
Marc 2014년 5월 22일
편집: Marc 2014년 7월 16일
My bad ... models is the vector containing the names. Using models{i} puts the files into models ... not exactly what I need :D using models(i) doesn't work. Using eval( )= doesn't work either no matter what I place within the brackets.
path=''; fprintf('Path: %s\n', path)
models={
'102030'
'30SR'
'30WHS1'
'30WHS2'
'40'
'4550'
'51'
'556077'
'200210220'
'230240'};
fprintf('Open Excel sheets:\n')
for i=1:length(models)
fprintf('\t Open %s\n', models{i})
xlsread(strcat(path,'\',models{i},'_PER.xlsx'));
end
Marc
Marc 2014년 5월 22일
Okay - in the meantime I switched to use structs instead of regular variables ... I thought too much in common programming languages ;)
Star Strider
Star Strider 2014년 5월 22일
See if evalin will do what you want.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2014년 5월 22일

편집:

2014년 7월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by