Reputation: 83
I'm trying to express a fuction with two variables, e.g:
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
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