tags:

views:

503

answers:

2

I'm trying to perform a really simple summation in MATLAB. Here is my code:

moment = 0;

for y=1:rows,
    for x=1:cols,
        moment = moment + (x^p * y^q * Im(y,x));
    end
end

I want (x^p * y^q * Im(y,x)) to be calculated for each iteration and added to the moment variable, but this function is returning the moment the first time it's calculated. It doesn't seem to do the adding at all.

Probably a stupid mistake, but I am really confused. Any suggestions?

A: 

put a breakpoint on the moment = moment + ... line and see if the variable "moment" is being increased.

I'm not sure why you use the comma in the for statement. It shouldn't have an effect, I don't think, but it's unnecessary.

Jason S
+4  A: 

Could it be that Im is of type uint8 or some similar type of small range? Try putting this line before the loops:

Im = double(Im);


BTW you can rewrite your code in one line:

moment = sum(sum( ((1:rows)'.^q * (1:cols).^p) .* double(Im) ));
Amro
Yes, Im is of type uint8, but it works now. Thank you!
Domenic
It looks like `p` and `q` may be reversed in your one-line solution.
gnovice
@gnovice: fixed, good catch
Amro

related questions