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!