Home > OS >  How can I sum rows 1 and 3 of my matrix in Matlab with the function sum()?
How can I sum rows 1 and 3 of my matrix in Matlab with the function sum()?

Time:10-30

I have matrix A= [1 1 4; 4 4 2; 1 2 4] and I need to sum the first and third row together and get (1 1 4) (1 2 4) using functions of Matlab, such as sum(), not only while and for. I know how to count it one by one, using for.

I tried to use sum in different ways, but I always get the sum of the whole matrix

CodePudding user response:

A lot of working with Matlab is accessing rows and columns of arrays. This is a reasonable first problem.

%Input
A = [1 1 4; 4 4 2; 1 2 4]

%Written out, row sum
out_1 = A(1,:)   A(3,:)

%Using the sum function, row sum
out_2 = sum(  A([1 3],:)  )

%To get the desired single value, I usually use `sum` twice, like this
out_scalar = sum(sum(  A([1 3],:)  ))

%But, if you are using 2018b or later, you can do this instead
out_scalar = sum(  A([1 3],:) , 'all')
  • Related