How can i replace all positive values of a matrix whit their square root ?

13 views (last 30 days)
I need to replace every positive value from this matix whit their square root
A = [1 1 2 3 5 8; 0 2 4 6 8 10; -1 -3 -5 -7 -9 -11;2 4 8 16 32 64;13 21 34 55 89 144];
i tried this
A(A>0)=sqrt(A)
but it doesn't work and MATLAB show me this error
Unable to perform assignment because the left and right sides have a different number of elements.

Answers (1)

John D'Errico
John D'Errico on 19 Mar 2020
Edited: John D'Errico on 19 Mar 2020
If you need to do it in one line, this will work:
A(A>0) = sqrt(A(A>0));
Or, you could do the test in advance, saving some CPU cycles.
So, why did your original idea not work? Because sqrt(A) has numel(A) elements in the result. However, A(A>0) does not have that many elements. So MATLAB tries to fit a square peg into a round hole, and then gives up. Unless you do as I suggested.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!