フィルターのクリア

Sum matrixes from cells

1 回表示 (過去 30 日間)
Christos
Christos 2024 年 3 月 9 日
回答済み: Sibghat 2024 年 3 月 9 日
Right now the code gives A matrix which are saved as cells in C. What I want to do at the final step, is to sum all A matrix that was given in every loop. How can I do that? Maybe exctract the matrix from C and sum them all together?! I dont know.( k is a number)
clear
clc
format long
k = input("mesie:");
for i=1:k
A=zeros(k+1);
L=zeros(2,k+1);
L(1,i)=1;
L(2,i+1)=1;
M1 = [2 1;1 2];
A = L'*M1*L;
C{i}=A;
end

採用された回答

Voss
Voss 2024 年 3 月 9 日
sum(cat(3,C{:}),3)
  3 件のコメント
Voss
Voss 2024 年 3 月 9 日
Demonstration:
clear
clc
format long
% k = input("mesie:");
k = 5;
for i=1:k
A=zeros(k+1);
L=zeros(2,k+1);
L(1,i)=1;
L(2,i+1)=1;
M1 = [2 1;1 2];
A = L'*M1*L;
C{i}=A;
end
A_total = sum(cat(3,C{:}),3)
A_total = 6×6
2 1 0 0 0 0 1 4 1 0 0 0 0 1 4 1 0 0 0 0 1 4 1 0 0 0 0 1 4 1 0 0 0 0 1 2
Voss
Voss 2024 年 3 月 9 日
You're welcome!

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

その他の回答 (1 件)

Sibghat
Sibghat 2024 年 3 月 9 日
Hopefully this will help...
clear
clc
format long
% The 'input' function can not be used here. So I have set a default value 3 for the variable k.
k = 3;
C = cell(1, k); % Preallocate cell array
summed_matrix = zeros(k+1); % Initialize summed_matrix
for i = 1:k
A = zeros(k+1);
L = zeros(2, k+1);
L(1, i) = 1;
L(2, i+1) = 1;
M1 = [2 1; 1 2];
A = L' * M1 * L;
C{i} = A;
% Accumulate each matrix into summed_matrix
summed_matrix = summed_matrix + A;
end
% Display all matrices stored in cell array C
for i = 1:k
disp(['Matrix C{' num2str(i) '}']);
disp(C{i});
end
Matrix C{1}
2 1 0 0 1 2 0 0 0 0 0 0 0 0 0 0
Matrix C{2}
0 0 0 0 0 2 1 0 0 1 2 0 0 0 0 0
Matrix C{3}
0 0 0 0 0 0 0 0 0 0 2 1 0 0 1 2
disp('Sum of all matrices:');
Sum of all matrices:
disp(summed_matrix);
2 1 0 0 1 4 1 0 0 1 4 1 0 0 1 2

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by