Reputation: 25
I have a matrix A
of an image with elements from 0 to 255. Now I want only the elements which are > 48
and < 200
to be changed to their square root.
I know I can find and replace elements like this:
A(A>48 & A<200) = 3;
But I don't want to set the elements to a number, I want to use the elements value for the new value.
Something like this:
A(A>48 & A<200).^(1/2)
The above syntax is obviously not correct, but I would like to calculate the square root of the elements which are > 48
and < 200
Is there a way without loops?
Upvotes: 1
Views: 266
Reputation: 104535
You're pretty close:
A(A>48 & A<200) = A(A>48 & A<200).^(1/2);
A > 48 & A < 200
creates a logical
mask to apply an operation only to specific entries in A
. Therefore, if you only want to select out those elements that are > 48
and < 200
, do so but then when you apply the operation make sure you assign back to only those positions.
If you want less typing, create the mask separately, then do the assignment:
mask = A > 48 & A < 200;
A(ind) = A(ind).^(0.5);
As recommended by Troy Haskin, it is better to actually use sqrt
instead of taking the half-power as sqrt
is a specialized operation and is optimized.
Therefore, do this instead:
mask = A > 48 & A < 200;
A(ind) = sqrt(A(ind));
Upvotes: 4