Breaking a Loop to Add Matrices

조회 수: 1 (최근 30일)
Chris Dan
Chris Dan 2019년 11월 14일
답변: Chris Dan 2019년 11월 18일
Hello Guys, I have a small problem regarding loops and matrices addition. I am trying to break the loop and add matrices diagnoally.
The situation is I have a code which adds matrices stored in a struct diagnoally. Here is my code:
S(1).model_data = sparse( rand( 3, 3 )) ;
S(2).model_data = sparse( rand( 3, 3 )) ;
S(3).model_data = sparse( rand( 3, 3 )) ;
S(4).model_data = sparse( rand( 3, 3 )) ;
S(5).model_data = sparse( rand( 3, 3 )) ;
S(6).model_data = sparse( rand( 3, 3 )) ;
C = sparse( rand( 3, 3 )) ;
s = size(S(1).model_data,1); % size of struct
n = size(S,2) ; % number of matrices in the struct
b = s+(s-1)+(n-2)*(s-1); % size of resulting matrix
T = sparse(b,b) % resulting matrix
for k = 1:1:n
for i = 1:1:s
for j = 1:1:s
m =(k-1)*(s-1);
T(i+m,j+m)= T(i+m,j+m) +S(k).model_data(i,j)
end
end
end
What I have to do is to run the loop till it reaches S(3), take the result, add C matrix to it diagnoally and then run the loop again to add S(4), S(5) and S(6) to it
so in the end our T matrix would be like:S1+S2+S2+C+S4+S5+S6
We cannot include C matrix in the struct, it HAS to be OUTSIDE of struct.
  댓글 수: 2
Mil Shastri
Mil Shastri 2019년 11월 14일
I'm not certain I understand your question correctly, but if I do, you could perfrom matrix addition of S and C_. Something like this:
S = [1,2,3,4,5,6]
C_ = [0,0,0,10,0,0]
S+C_
ans =
1 2 3 14 5 6
Chris Dan
Chris Dan 2019년 11월 15일
this way matrices are not overlapping each other, they should bbe added in way that the last elelment of the first matrix and the first matrix of the second matrix adds up and matrices are placed diagnoally in a bigger matrix

댓글을 달려면 로그인하십시오.

채택된 답변

Chris Dan
Chris Dan 2019년 11월 18일
here is the answer, I jsut figured it out
S(1).model_data = sparse( rand( 3, 3 )) ;
S(2).model_data = sparse( rand( 3, 3 )) ;
S(3).model_data = sparse( rand( 3, 3 )) ;
S(4).model_data = sparse( rand( 3, 3 )) ;
S(5).model_data = sparse( rand( 3, 3 )) ;
S(6).model_data = sparse( rand( 3, 3 )) ;
C = sparse( rand( 3, 3 )) ;
s = size(S(1).model_data,1); % size of struct
n = size(S,2)+1;% number of matrices in the struct
b = s+(s-1)+(n-2)*(s-1); % size of resulting matrix
T = sparse(b,b); % resulting matrix
counter = 0;
for k = 1:1:n
for i = 1:1:s
for j = 1:1:s
m =(k-1)*(s-1);
if (k == 4)
T(i+m,j+m)= T(i+m,j+m) +C(i,j);
counter = 1;
else
T(i+m,j+m)= T(i+m,j+m) +S(k-counter).model_data(i,j);
end
end
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by