How can I use the output of "sprintf" to read the content of a matrix
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
Jos (10584)
2013-12-3
Avoid eval!
Why? Try this:
eval(char('chro''&Xntqbnlotsdqg`raddmg`bjdc-&('+1))
Did you expect that?
更多回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!