0

My question is that given an array A, how can you give another array identical to A except changing all negatives to 0 (without changing values in A)?

My way to do this is:

B = A;

B(B<0)=0

Is there any one-line command to do this and also not requiring to create another copy of A?

2
  • Your questions seems self contradictory, you want another array identical to A but also do not want to create a copy of A. Commented Sep 12, 2016 at 22:37
  • 2
    You can use max(A,0) Commented Sep 12, 2016 at 22:37

2 Answers 2

2

While this particular problem does happen to have a one-liner solution, e.g. as pointed out by Luis and Ian's suggestions, in general if you want a copy of a matrix with some operation performed on it, then the way to do it is exactly how you did it. Matlab doesn't allow chained operations or compound expressions, so you generally have no choice but to assign to a temporary variable in this manner.

However, if it makes you feel better, B=A is efficient as it will not result in any new allocated memory, unless / until B or A change later on. In other words, before the B(B<0)=0 step, B is simply a reference to A and takes no extra memory. This is just how matlab works under the hood to ensure no memory is wasted on simple aliases.


PS. There is nothing efficient about one-liners per se; in fact, you should avoid them if they lead to obscure code. It's better to have things defined over multiple lines if it makes the logic and intent of the algorithm clearer.

e.g, this is also a valid one-liner that solves your problem:

B = subsasgn(A, substruct('()',{A<0}), 0)

This is in fact the literal answer to your question (i.e. this is pretty much code that matlab will call under the hood for your commands). But is this clearer, more elegant code just because it's a one-liner? No, right?

Sign up to request clarification or add additional context in comments.

Comments

1

Try

B = A.*(A>=0)

Explanation:

A>=0 - create matrix where each element is 1 if >= 0, 0 otherwise

A.*(A>=0) - multiply element-wise

B = A.*(A>=0) - Assign the above to B.

2 Comments

Ian Riley, this is not a correct answer. This will result in a vector containing only the elements of A that are above 0. Not a matrix the size of A with negatives zeroed.
My apologies- I misunderstood the original question. Does this answer it better? Luis's answer is correct, but I wanted to be more general (if you wanted to do something like take primes, or take odds, or something)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.