How to save the result of each loop separately

5 ビュー (過去 30 日間)
Olayinka
Olayinka 2023 年 11 月 21 日
回答済み: Mathieu NOE 2023 年 11 月 21 日
I want to create two variables which are matrices is zeros(3,2) and zeros(4,2)
y = [3 4];
for i=1:length(y)
x=zeros(y(i),2)
end
x = 3×2
0 0 0 0 0 0
x = 4×2
0 0 0 0 0 0 0 0
I dont want the second loop to overwrite the result of the first loop.

採用された回答

Paul
Paul 2023 年 11 月 21 日
One option is to use a cell array to store dissimilar objects
y = [3 4];
for i=1:length(y)
x{i}=zeros(y(i),2)
end
x = 1×1 cell array
{3×2 double}
x = 1×2 cell array
{3×2 double} {4×2 double}
Though not shown here, x can be preallocated based on the number of elements in y.

その他の回答 (2 件)

Les Beckham
Les Beckham 2023 年 11 月 21 日
Perhaps this (using a cell array)?
y = [3 4];
for i = 1:length(y)
x{i} = zeros(y(i), 2)
end
x = 1×1 cell array
{3×2 double}
x = 1×2 cell array
{3×2 double} {4×2 double}

Mathieu NOE
Mathieu NOE 2023 年 11 月 21 日
hello
some solutions :
y = [3 4];
for k=1:length(y)
% solution 1 : store as cell array
x{k} =zeros(y(k),2);
% solution 2A : store as structure
s(k).data =zeros(y(k),2);
% solution 2B : another structure
t.data{k} =zeros(y(k),2);
end
x
x = 1×2 cell array
{3×2 double} {4×2 double}
s
s = 1×2 struct array with fields:
data
t
t = struct with fields:
data: {[3×2 double] [4×2 double]}

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by