Loop for matrix summation

6 views (last 30 days)
Perez Danny
Perez Danny on 4 Apr 2021
Commented: Perez Danny on 4 Apr 2021
Hello, sorry if my question is stupid, I am a beginner in matlab
I would like to do a 3*3 matrix sumation (element by element). More in detail: I am working with a matlab fuction which output is a 3*3 matrix, the input is 3 column data (strr1,dpr1and rkr1). Then I would like to divide each matrix obtained from the input (280 elements, so I have 280 3*3 matrix) by a scalar, and finally, from that result I would like to sume each matrix to get a single 3*3 matrix (the result of the summation of all matrix calculated by the function). Next, a small script about my problem
Thanks for your attention
strr1=(tw1r1(:,12)); %%input1
dpr1=(tw1r1(:,14)); %%input2
rkr1=(tw1r1(:,16)); %%input3
mtr11w1s=zeros(3,3) %% I created this matriw for storing the final summation
for rr1=1:length(strr1) %%% loop for calculating the 280 3*3 matrix from thre 3 inputs
mtr1=SDR2MT(strr1( rr1),dpr1( rr1),rkr1( rr1)) %%%% Result: 280 3*3 matrix
mtr1n=mtr1/length(tw1r1) %%%%Escalar division for each element of the 3*3 matrix
for z=1:length(mtr1n) %%%% Here I try to do a loop for doing the summation of 280 3*3 matrix
mtr11w1s= mtr11w1s+mtr1n(z)
end
end

Accepted Answer

DGM
DGM on 4 Apr 2021
I'm not sure what tw1r1 is supposed to be. I'm going to substitute something there.
mytestnumber=37;
mtr11w1s=zeros(3,3);
for rr1=1:numel(strr1)
%mtr1=SDR2MT(strr1( rr1),dpr1( rr1),rkr1( rr1)) %%%% Result: 280 3*3 matrixm
mtr1=ones(3); % i don't have SDR2MT, so this is just a dummy
mtr1n=mtr1/mytestnumber;
for z=1:numel(mtr1n)
%mtr11w1s=mtr11w1s+mtr1n(z); % you sure you don't mean to be doing
mtr11w1s(z)=mtr11w1s(z)+mtr1n(z); % something like this?
end
end
mtr11w1s
I'm still not really sure if this is doing what you intend it to do. Do you have a written expression for the summation you're trying to do?
Also, as a tip:
a=rand(3,3); [length(a) numel(a)]
shows that if you want to step through all the linear indices of a 2D array, you shouldn't be using length()
ans =
3 9
  3 Comments
DGM
DGM on 4 Apr 2021
I take it that the results are as you expect?
Perez Danny
Perez Danny on 4 Apr 2021
Yeah, results are the expected.
Again, thanks for your help

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!