storing output (which are matrices) of for loops
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Stephen23
2018 年 6 月 6 日
編集済み: Stephen23
2018 年 6 月 6 日
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
その他の回答 (1 件)
Ankita Bansal
2018 年 6 月 6 日
編集済み: Ankita Bansal
2018 年 6 月 6 日
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 件のコメント
Stephen23
2018 年 6 月 6 日
Note that this does not preallcoate the output arrays, so will require the arrays to be resized and moved on each iteration.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!