philip
philip

Reputation: 35

function that replaces the negative numbers of an array with 77

function Z=replacez(A)
    [M,N]=size(A);
    for i=1:M
        for j=1:N
           if A(i,j)<0
              Z(i,j)=77;
           else
              Z(i,j)=A(i,j);
           end
      end
end

This is a simple function in MATLAB that replaces the negative numbers of an array A with the number 77.Can it be implemented without the for loops but with the find function instead?

So far I know the find(A<0) returns an array with the positions of the negative numbers of array A.For example A=[1 , 0 , -3; -4 , 1 , -2], find(A<0) will return ans=[3 ,4 , 6]

Upvotes: 1

Views: 133

Answers (1)

alpereira7
alpereira7

Reputation: 1550

If for some reason you really need to use find, I'll suggest your function to be

function Z = replacez(A)
  Z = A;
  Z(find(Z<0)) = 77;
end

But you should avoid it. Indeed, according to Matlab's find:

To directly find the elements in X that satisfy the condition X<5, use X(X<5). Avoid function calls like X(find(X<5)), which unnecessarily use find on a logical matrix.

find is redundant here and you could do

function Z = replacez(A)
  Z = A;
  Z(Z<0) = 77;
end

Upvotes: 4

Related Questions