MATLAB: Array addition in specific location

find

I have one array, h = [0 1 2 3 4 0 6 7 8 9 10];
And a formula, u = 1.24/h; Right now, I need to perform this calculation only at locations where h is greater than zero. And store the new array as "us".
Here is my script, us = zeros(1,10);
a = 1.24/h;
i = find(h>0);
us(i) = us(h>0) + a(i);
This code give me the first 8th value that h is greater than zero. However, how can I place them at locations where h is greater than zero?

Best Answer

Try this:
h = [0 1 2 3 4 0 6 7 8 9 10]
% Do the formula everywhere.
a = 1.24 ./ h
% Find those elements where h is > 0
elementsToReplace = find(h > 0)
% Initialize us to h
us = h;
% Now replace only those elements where h was greater than zero.
us(elementsToReplace) = a(elementsToReplace)