Clear Filters
Clear Filters

How to save Matrices which i created in a "for" loop?

2 views (last 30 days)
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.

Accepted Answer

Evan
Evan on 2 Jul 2013
Edited: Evan on 2 Jul 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.

More Answers (2)

Jan
Jan on 3 Jul 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 Comments
Jan
Jan on 3 Jul 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.
andreas
andreas on 3 Jul 2013
Thank you very much this a huge help for me.

Sign in to comment.


andreas
andreas on 3 Jul 2013
Thank you very much
  1 Comment
Jan
Jan on 3 Jul 2013
Please post comments to answers in the corresponding comment field, not as new answer. If your problem is solved, accept the corresponding answer, such that it is clear, that you do not need further help. Thanks.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!