MATLAB: Having problem to solve somthing in matlab

MATLABmatlab functionmatlab helpmatlab matrix

i have this question it says that i have a matrix A [m,n]
and i need to get the amount of the first row and the last row for example if i have a matrix like this :
7 5 3
9 1 8
10 1 3
i wanna get the first row ==> 7+5+3 =15
and the last row ==>10+1+3=14
and after that i need to do 15+14=29 ( as first row + the last row)
so the problem i have that i cant use sum function but i can use for
can anyone help me with this ?

Best Answer

If you think about how basic matrix, vector multiplication works, you can see that you can sum rows of a matrix by multiplying by a column vector of ones. You can sum selected elements of a column vector by premultplying by a row vector consisting of zeros and ones (with zeros for the elements that you don't want to include in the sum). Putting these ideas together in your case gives
y = [1 0 1]*A*[1;1;1]
You could also accomplish what you want using MATLAB's indexing abilities along with the sum function. Note that A(1,:) means row 1, every column of A. Similarly A(3,:) means row 3 every column of A
y = sum(A(1,:)) + sum(A(3,:))
Related Question