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

2 次查看(过去 30 天)
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.

采纳的回答

Evan
Evan 2013-7-2
编辑:Evan 2013-7-2
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.

更多回答(2 个)

Jan
Jan 2013-7-3
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 个评论
Jan
Jan 2013-7-3
@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 2013-7-3
Thank you very much
  1 个评论
Jan
Jan 2013-7-3
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by