storing output (which are matrices) of for loops
2 views (last 30 days)
Show older comments
Hello, I am trying to store my output from for loop to be used later in code. The output is a 2x4 matrix for each cycle of loop. here is my code.
B= [0.0250; 0.0500; 0.0750; 0.1000; 0.1250; 0.1500; 0.1750; 0.2000; 0.2250; 0.2500; 0.2750; 0.3000; 0.3250; 0.3500; 0.3750; 0.4000];
rig=0.01
for j=1:length(B)
k= B(j)/(2*rig)
TMP= [cos(k*l)^2, (sin(k*l)*cos(k*l))/k, sin(k*l)*cos(k*l), (sin(k*l)^2)/k;
-k*sin(k*l)*cos(k*l), cos(k*l)^2, -k*sin(k*l)^2, sin(k*l)*cos(k*l);
-sin(k*l)*cos(k*l), -(sin(k*l)^2)/k, cos(k*l)^2, (sin(k*l)*cos(k*l))/k;
k*sin(k*l)^2, -sin(k*l)*cos(k*l), -k*sin(k*l)*cos(k*l), cos(k*l)^2]
TM= TMP*TMP
C1=[TM(1,:);TM(3,:)]
end
I want to store C1 and k for each cycle of loop to be used later in other parts of code. please let me know what would be the best way to do so. I tried to do it by initializing an array (like we do for scalar outputs but this did not workout. Thank you very much for your help.
0 Comments
Accepted Answer
Stephen23
on 6 Jun 2018
Edited: Stephen23
on 6 Jun 2018
Array preallocation works for me:
l = 1;
B = [0.0250; 0.0500; 0.0750; 0.1000; 0.1250; 0.1500; 0.1750; 0.2000; 0.2250; 0.2500; 0.2750; 0.3000; 0.3250; 0.3500; 0.3750; 0.4000];
B = 0.025:0.025:0.4;
kV = nan(1,1,numel(B));
CM = nan(2,4,numel(B));
rig = 0.01;
for j = 1:numel(B)
k = B(j)/(2*rig);
TMP = [cos(k*l)^2, (sin(k*l)*cos(k*l))/k, sin(k*l)*cos(k*l), (sin(k*l)^2)/k;
-k*sin(k*l)*cos(k*l), cos(k*l)^2, -k*sin(k*l)^2, sin(k*l)*cos(k*l);
-sin(k*l)*cos(k*l), -(sin(k*l)^2)/k, cos(k*l)^2, (sin(k*l)*cos(k*l))/k;
k*sin(k*l)^2, -sin(k*l)*cos(k*l), -k*sin(k*l)*cos(k*l), cos(k*l)^2];
TMP = TMP*TMP;
CM(:,:,j) = [TMP(1,:);TMP(3,:)];
kV(j) = k;
end
More Answers (1)
Ankita Bansal
on 6 Jun 2018
Edited: Ankita Bansal
on 6 Jun 2018
Hi Sumera, you can do so by changing k to k(j) and C1 to C1(:,:,j).
B= [0.0250; 0.0500; 0.0750; 0.1000; 0.1250; 0.1500; 0.1750; 0.2000; 0.2250; 0.2500; 0.2750; 0.3000; 0.3250; 0.3500; 0.3750; 0.4000];
rig=0.01
for j=1:length(B)
k_1(j)= B(j)/(2*rig)
k=k_1(j);
TMP= [cos(k*l)^2, (sin(k*l)*cos(k*l))/k, sin(k*l)*cos(k*l), (sin(k*l)^2)/k;
-k*sin(k*l)*cos(k*l), cos(k*l)^2, -k*sin(k*l)^2, sin(k*l)*cos(k*l);
-sin(k*l)*cos(k*l), -(sin(k*l)^2)/k, cos(k*l)^2, (sin(k*l)*cos(k*l))/k;
k*sin(k*l)^2, -sin(k*l)*cos(k*l), -k*sin(k*l)*cos(k*l), cos(k*l)^2]
TM= TMP*TMP
C1(:,:,j)=[TM(1,:);TM(3,:)]
end
Here i have stored values in k_1.
Hope this helps.
2 Comments
Stephen23
on 6 Jun 2018
Note that this does not preallcoate the output arrays, so will require the arrays to be resized and moved on each iteration.
See Also
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!