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

logical indexingMATLAB

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?

Best Answer

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