How to save Matrices which i created in a "for" loop?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
This is my current code:
clc M = dec2bin(0:2^15-1, 15); A=zeros(5);
for i=1:2^15
A(1,1:5)=[str2num(M(i,1)),str2num(M(i,2)),str2num(M(i,3)),str2num(M(i,4)),str2num(M(i,5))];
A(2,2:5)=[str2num(M(i,6)),str2num(M(i,7)),str2num(M(i,8)),str2num(M(i,9))];
A(3,3:5)=[str2num(M(i,10)),str2num(M(i,11)),str2num(M(i,12))];
A(4,4:5)=[str2num(M(i,13)),str2num(M(i,14))];
A(5,5)=[str2num(M(i,15))];
end;
At the moment i am not able to use the matrices i created during the loop. Is there a way to save them, so that i can later use them again?
Could you please include the answer into this code, because i am quite new to matlab.
Thank you very much for your help.
Réponse acceptée
Evan
le 2 Juil 2013
Modifié(e) : Evan
le 2 Juil 2013
You could create a 3D matrix in order to not lose each value on the next iteration. Just add a third dimension in your indexing:
for i=1:2^15
A(1,1:5,i) =[str2num(M(i,1)),str2num(M(i,2)),str2num(M(i,3)),str2num(M(i,4)),str2num(M(i,5))];
A(2,2:5,i)=[str2num(M(i,6)),str2num(M(i,7)),str2num(M(i,8)),str2num(M(i,9))];
A(3,3:5,i)=[str2num(M(i,10)),str2num(M(i,11)),str2num(M(i,12))];
A(4,4:5,i)=[str2num(M(i,13)),str2num(M(i,14))];
A(5,5,i)=[str2num(M(i,15))];
end
You'll now have a 5x5x2^15 size matrix, where each "layer" is the result from each iteration of your loop.
1 commentaire
James Tursa
le 3 Juil 2013
Just be sure to preallocate for this case, e.g.,
A=zeros(5,5,2^15);
Plus de réponses (2)
Jan
le 3 Juil 2013
Note: You can omit the large number of STR2NUM calls, if you convert M initially:
M = dec2bin(0:2^15-1, 15) - '0'; % Implicite conversion to DOUBLE
A = zeros(5, 5, 2^15);
for i = 1:2^15
A(1,1:5,i) = M(i,1:5); % Do we need a RESHAPE here?
...
end
Of course you could look into the code of DEC2BIN and avoid the temporary conversion to a CHAR array also. And finally the FOR loop is not required also:
A(1, :, :) = reshape(M(:, 1:5)', 1, 5, 2^15);
etc.
Sorry, I cannot test this currently.
3 commentaires
Jan
le 3 Juil 2013
@andreas: In the posted code the index is moved from the FOR loop directly into the assignement. So in "A(1, 1:5, i)" the "i" is replaced by "1:2^15". And because A has the required size already, "1:2^15" can be replaced by ":".
I try to test this in the evening and post a complete code then.
You are welcome in the forum and it is the nature of beginning that details have to be learned.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!