2

I have an array in matlab, e.g.

a=rand([3,3])
a =

0.8308    0.9172    0.7537
0.5853    0.2858    0.3804
0.5497    0.7572    0.5678

And now, I would like to set the min value of each row to 0. The result should be:

a =

0.8308    0.9172    0
0.5853    0         0.3804
0         0.7572    0.5678

I have no idea how to use [Y,I]=min(a,[],2) function for this. Thanks.

3 Answers 3

3

As you said, you can get the column index of the minimal value of each row using

[~, col] = min(a, [], 2);

Now you can use sub2ind to set the entries to zero:

a( sub2ind(size(a), 1:size(a,1), col.') ) = 0;

You can play with it on ideone.

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

6 Comments

Error: Unbalanced or unexpected parenthesis or bracket. I clear the last bracket, but still do not work..
Error using sub2ind The subscript vectors must all be of the same size. Still not working.
@IvoVertat fixed.
Excellent. Great job. Thanks.
@IvoVertat if this solution worked for you, please consider "accepting" it by clicking the "v" icon beside it. thanks!
|
2

If you are concern about multiple minima in the same row:

row_min = min(a, [], 2);
a( bsxfun(@eq, row_min, a) ) = 0;

No loops are needed (as opposed to Matt T's answer).

1 Comment

It works well and easy to extend for multidimensional array. Thanks
0

One inefficient method would be to loop through each row and use the find command to find all minima in a particular row.

n = 10;
A = rand(n,n);    
for ii = 1:n
ind = find(A(ii,:) == min(A(ii,:)));
A(ii,ind) = 0;
end

If there are multiple minima, this will set all of these to zero.

Hope this helps.

1 Comment

no need for loop. better use logical indexing instead of find.

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.