MATLAB: How to add a specific number to elements in a vector

arraymatrix manipulation

Hi,
I have a 1×600 matrix called 'samples' containing numbers from 0 to 255. I want to add the number 255 to every element in the array that is less than 100. I also want to divide the matrix into two different matrices, one contains the elements 0 to 300 and the other one from 301 to 600. I am able to divide the matrix in 2, but when I add the value 255 to every element less than 100 it adds it to all the elements in the matrix. How can I fix my error? Thanks! The code I have so far is
%samples is a 1x600 matrix
frames = 300;
on = wkeep(samples,frames,[frames+1 1]);
off = wkeep(samples,frames,[1 1]);
if any (on < 100)
on_count = on + 255;
end
if any (off < 100)
off_count = off +255 ;
end

Best Answer

if any (on < 100)
on_count = on + 255;
end
says: if any element of on is less than 100 (1st), then set on_count to the sum of on (hence all the elements of on) with 255. So, if any element of on is less than 100, you add 255 to all the element of on and put it in a new on_count variable. If none of the elements of on are less than 100, then nothing happens, on_count is not even created.
The correct way:
on_count = on; %copy everyting
mask = on_count < 100; %logical vector telling you which elements to change
on_count(mask) = on_count(mask) + 100; %only change those elements for which the mask is true
Same for off. No if or for needed.
edit: another way to obtain the same result with no comparison at all, just using mathematical operations would be:
on_count = mod(on - 100, 255) + 100;