Using logical indexing to modify non-negative elements of a matrix

I need to pass a matrix of radii to the function areaCircle and have it output a matrix the same size of the input with the respective areas in the entries with non-negative radius and -1 in the entries with negative radius as error signaling.
I am trying this
function area = areaCircle(r)
nim = r < 0 %negative-index matrix
r(nim) = -1 % sets the negative entries of the r matrix to -1
area = zeros(size(r));
area(nim)= pi.*r.*r ;% ? this doesn't work
end
How can I achieve it?

2 commentaires

What does non-begative mean?
just a typo, I meant non-negative. Thanks

Connectez-vous pour commenter.

 Réponse acceptée

Alan Stevens
Alan Stevens le 26 Sep 2020
Modifié(e) : Alan Stevens le 26 Sep 2020
Try
function area = areaCircle(r)
nim = r < 0; %negative-index matrix
area = zeros(size(r));
area= pi.*r.*r ;
area(nim) = -1; % sets the negative entries of the area matrix to -1
end

3 commentaires

Can logical indexing be used to modify the matrix before the operation is done, as I was trying to do?. This might not work if instead of raising to a power I had to take log or or do a square root
You could do
r(nim) = NaN;
before the area/log/power etc operation.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by