"cycle for" between matrix with a variable in the name

Hi;
I have a series of matrix like A1, A2....AN and i want to perform an operation like
for i=1:N
B=B+A"i"(:,2)
end
how do i have to format the A"i"(:,2) part?
thank you

1 件のコメント

Steven Lord
Steven Lord 2024 年 10 月 30 日
Can you dynamically create variables with numbered names like A1, A2, A3, etc.? Yes.
Should you do this? The general consensus is no. That Discussions post explains why this is generally discouraged and offers several alternative approaches.

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

 採用された回答

Shivam
Shivam 2024 年 10 月 30 日

0 投票

Hi Andrea,
Refer to the example implementation:
N = 5; % Example no of matrix
A = {A1, A2, A3, A4, A5}; % Cell array containing matrices
% Initialize B
B = zeros(size(A{1}, 1), 1); % Assuming all matrices have the same number of rows
% Perform the operation
for i = 1:N
B = B + A{i}(:, 2);
end

3 件のコメント

Andrea
Andrea 2024 年 10 月 30 日
Thank you for your answer, but i realized my problem is a little more complicated because I am working with struct of the type B.C1, B.C2....B.C100. So my code line is
for i=1:100
A=A+B.(C{i})(:,12);
end
i tried with and without (), but i had the error: Undefined variable 'C'.
Do you know how can I solve this too? I searched on this site but didn't find a solution.
Voss
Voss 2024 年 10 月 30 日
A = zeros(size(B.C1,1),1);
for ii = 1:100
A = A + B.("C"+ii)(:,12);
end
Stephen23
Stephen23 2024 年 10 月 30 日
"...I am working with struct of the type B.C1, B.C2....B.C100"
Rather than forcing pseudo-indices into the fieldnames it would be simpler and more efficient to use actual indexing.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

質問済み:

2024 年 10 月 30 日

コメント済み:

2024 年 10 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by