Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (1)

Jos (10584)
Jos (10584) el 3 de Dic. de 2013
Editada: Jos (10584) el 3 de Dic. de 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

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by