Effacer les filtres
Effacer les filtres

Breaking a Loop to Add Matrices

1 vue (au cours des 30 derniers jours)
Chris Dan
Chris Dan le 14 Nov 2019
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 commentaires
Mil Shastri
Mil Shastri le 14 Nov 2019
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 le 15 Nov 2019
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

Connectez-vous pour commenter.

Réponse acceptée

Chris Dan
Chris Dan le 18 Nov 2019
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

Plus de réponses (0)

Catégories

En savoir plus sur Sparse Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by