Breaking a Loop to Add Matrices
조회 수: 1 (최근 30일)
이전 댓글 표시
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
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
채택된 답변
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!