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
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