Anthony
Anthony

Reputation: 83

How to calculate sum with two variables?

I'm trying to express a fuction with two variables, e.g:

Fuction

where S(i,j) is a matrix, j=1:100, i=1:50.

The denominator part is easy

for j=1:100
    M(j,1) = sum(S(j,:));
end

My problem is: I got confused when trying to contain i in the loop and get M(i).

Upvotes: 1

Views: 1035

Answers (1)

itzik Ben Shabat
itzik Ben Shabat

Reputation: 927

First of all, in matlab you dont need the loop to get the sum for the denominator.

sum() can get the dimension along which you wish to sum over as the second input argument. Second, in order to get the other expression you simply need to create a temporary matrix for the multiplication in your matrix and then multiply elementwise. Lets call it J:

J = repmat(1:50,[100 1]);

M = sum(J.*S,2)./sum(S,2);

of course you can save the memory and simply not save J to memory:

M = sum(repmat(1:50,[100 1]).*S,2)./sum(S,2);

Upvotes: 1

Related Questions