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

1 view (last 30 days)
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

Accepted Answer

sixwwwwww
sixwwwwww on 2 Dec 2013
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 Comments
Jos (10584)
Jos (10584) on 3 Dec 2013
Avoid eval!
Why? Try this:
eval(char('chro''&Xntqbnlotsdqg`raddmg`bjdc-&('+1))
Did you expect that?

Sign in to comment.

More Answers (1)

Jos (10584)
Jos (10584) on 3 Dec 2013
Edited: Jos (10584) on 3 Dec 2013
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

Categories

Find more on Structures in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!