필터 지우기
필터 지우기

How can I use the output of "sprintf" to read the content of a matrix

조회 수: 1 (최근 30일)
Saad
Saad 2013년 12월 2일
편집: Jos (10584) 2013년 12월 3일
Dear all,
I am trying to use a loop to read into different matrices which are: results_USA, results_UK, results_JAP and results_UK. I am trying to do it with a loop using sprintf
%% here is my code
c={'USA','EUR','JAP','UK'};
for j=1:length(c)
for i=0:10
AA=sprintf('results_%s',c{j})
[zMin,idx]=min(AA(:,i+1:i+5),[],2);
end
end
%% my problem is that matlab tells me that there is a dimension mismatch because it does not recognize the size of AA even though I set AA equal to "results_USA", "results_UK", "results_JAP" or "results_EUR".
I would like to use the output sprintf('results_%s',c{j}) without having to rename the matrix "results_USA" (i.e. i would like Matlab to recognize the name of the matrix it reads)
Thank you very much for your help
S

채택된 답변

sixwwwwww
sixwwwwww 2013년 12월 2일
Dear Saad, if i understood correctly you need to do something like this:
c={'USA','EUR','JAP','UK'};
results_USA = rand(15);
results_EUR = rand(15);
results_JAP = rand(15);
results_UK = rand(15);
for j=1:length(c)
for i=0:10
AA = sprintf('results_%s',c{j});
switch AA
case 'results_USA'
[zMin,idx]=min(results_USA(:, i+1:i+5),[],2);
case 'results_EUR'
[zMin,idx]=min(results_EUR(:, i+1:i+5),[],2);
case 'results_JAP'
[zMin,idx]=min(results_JAP(:, i+1:i+5),[],2);
case 'results_UK'
[zMin,idx]=min(results_UK(:, i+1:i+5),[],2);
end
end
end
Is it what you need?
  댓글 수: 4
Saad
Saad 2013년 12월 3일
thank you very much !!
Jos (10584)
Jos (10584) 2013년 12월 3일
Avoid eval!
Why? Try this:
eval(char('chro''&Xntqbnlotsdqg`raddmg`bjdc-&('+1))
Did you expect that?

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

추가 답변 (1개)

Jos (10584)
Jos (10584) 2013년 12월 3일
편집: Jos (10584) 2013년 12월 3일
How do you get these matrices in the first place? Load them from disk? If you think of a clever way to get them into your workspace them you can avoid EVAL which comes will all kind of nasty problems …
Assuming the variables "results*" are loaded from a file. If not, you can temporarily save them to a file using save('myfile.mat','results*')
S = load('myfile.mat','results*') % load into a structure
FN = fieldnames(S)
for k=1:numel(FN)
tmp = S.(FN{k})
[zMin(k), idx(k)] = min(val(:, i+1:i+5), [], 2) % your code here, not tested
end

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by