1

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?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Butti
  • 25
  • 2

1 Answers1

4

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);

Minor Note

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));
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • does it need to be `&&` instead of `&` ? – costrom Apr 19 '16 at 16:51
  • 3
    @costrom No. Not for matrices or arrays at least. It is required that you use `&` because matrices do not support short-circuiting behaviour. You **must** check the condition for every array / matrix that is within the chain of operations. `&&` is usually applied to scalars by convention and `A` is definitely not a scalar. See this post: http://stackoverflow.com/questions/1379415/whats-the-difference-between-and-in-matlab... and in particular, user gnovice's comment: http://stackoverflow.com/questions/1379415/whats-the-difference-between-and-in-matlab#comment1218885_1379460 – rayryeng Apr 19 '16 at 16:52
  • 2
    @costrom I'd also note that calling the `sqrt` function is generally faster than taking the matrix to the 0.5 power, mainly because the operation is specialized and Matlab's parser doesn't want to or can't re-write the expression to that form. On my system, `sqrt` is about twice as fast. – TroyHaskin Apr 19 '16 at 18:21
  • @TroyHaskin Nice. I'll put that into my post. – rayryeng Apr 19 '16 at 18:31
  • Thanks a lot!! My first question at stackoverflow, works great! – Butti Apr 21 '16 at 11:19
  • @Butti you're very welcome. Please consider accepting my answer to let the community know you no longer need help. That can be done by clicking on the checkmark icon at the top of my answer to the left, below the up and down voting arrows. Good luck! – rayryeng Apr 21 '16 at 13:18