フィルターのクリア

How can I save data from for loop?

16 ビュー (過去 30 日間)
majid
majid 2024 年 4 月 13 日
回答済み: Vaibhav 2024 年 7 月 25 日 5:56
Hello.
I have 3 arrays of scalar number. I want to have some simple calculation on all numbers of these 3 arrays one by one (Permutation of all arrays numbers ), then multiplying every result (y) with rand(4,20) and finally saving every result as a excel data. I wrote the below codes but I have some problem: "I see in the output only the last multipication result of y" and therefore just last w.
clc
clear all
i=0;
j=1;
n=1;
A = [10 20 30 40 50 10];
B = [1 1.2 1.4 1.6 1.8 1];
C = [5 25 45 65 85 5];
z= rand(4,20);
for a = 1:125
i=i+1;
if i==6
j=j+1;
i=1;
end
if j==6
n=n+1;
j=1;
end
if(n==6)
n=1;
break ;
end
A_2 = A(i);
B_2 = B(j);
C_2 = C(n);
y = A_2 * B_2 * C_2 - A_2 * C_2;
w = y * z;
end
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2024 年 4 月 13 日
"I see in the output only the last multipication result of y" and therefore just last w."
Preallocate w and use indexing (i.e. loop variable a) to save the values in it.
majid
majid 2024 年 4 月 13 日
thankyou for your answeing.

サインインしてコメントする。

回答 (1 件)

Vaibhav
Vaibhav 2024 年 7 月 25 日 5:56
Hi Majid
Code is overwriting the variable w in each iteration of the loop, so only the result from the last iteration is saved. To store all the results, you can save each w in a cell array or a 3D matrix. Below is a modified version of your code that saves each result in a cell array.
clc;
clear all;
i = 0;
j = 1;
n = 1;
A = [10 20 30 40 50 10];
B = [1 1.2 1.4 1.6 1.8 1];
C = [5 25 45 65 85 5];
z = rand(4,20);
% Initialize cell array to store results
results = cell(125, 1);
for a = 1:125
i = i + 1;
if i == 6
j = j + 1;
i = 1;
end
if j == 6
n = n + 1;
j = 1;
end
if n == 6
n = 1;
break;
end
A_2 = A(i);
B_2 = B(j);
C_2 = C(n);
y = A_2 * B_2 * C_2 - A_2 * C_2;
w = y * z;
% Store the result in the cell array
results{a} = w;
end

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by