Reputation: 786
I have a Matrix A = [1 2 -3; 4 5 -2]. Now without using for loop, I want to filter the array in such a way so that any value less than 0 will return 0. So, the output matrix will be RES = [1 2 0; 4 5 0].
any link / sample code to solve the problem would be greatly appreciated.
Upvotes: 2
Views: 3982
Reputation:
There are several ways to do this, as shown by others. What you need to appreciate are the choices you have, as sometimes one solution or another will be best. So try this:
RES = max(A,0);
It takes the larger of 0 or A(i) for each element in the result. A nice thing is this solution requires only one line since you need not preallocate a result.
Upvotes: 3
Reputation: 12345
RES = A;
RES(RES<0)=0
RES<0
produces a logical array, in this case [false false true; false false true]
. Then the notation RES(RES<0)=
allows you to set all the values what are true to some value.
This is a pretty typical, and useful, Matlab idiom.
Upvotes: 4