Could anyone help me how to solve the issue

I am having a matrix
A=[0.0088 0.0071 0.0058 0.0049 0.0045 0.0045;
0.0255 0.0248 0.0241 0.0234 0.0227 0.0218;
1.8321 2.0932 2.3378 2.5582 2.7400 2.8653;
0.0666 0.0605 0.0559 0.0526 0.0505 0.0491;
0.0322 0.0294 0.0303 0.0334 0.0372 0.0410]
to find the maximum value in each row i used the command max(A,[],2) which gives the result.
But i need to have the output in such a way that the matrix needs to be displayed holding only the maximum value and rest of the other values should be zero.
Could anyone please help me on this.

 Accepted Answer

madhan ravi
madhan ravi on 31 Jul 2019
Edited: madhan ravi on 31 Jul 2019
[v,idx] = max(A,[],2);
Wanted = zeros(size(A));
Wanted(sub2ind(size(A),(1:size(A,1)).',idx)) = v

7 Comments

with respect to the command line
Wanted(idx) = v
i am getting the result as
Wanted =[0.0666 0.0410 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0;
0 0 0 0 0 0]
could you please help me on this.
with respect to command line Wanted(sub2ind(size(A),(1:size(A,1)).',idx)) = v it works fine.
Could you please help me how to find two maximum values in each row of matrix.
Try the edited answer.
Yes i tried.Could you please help me how to find two maximum values in each row.
[v,idx]=maxk(A,2,2)
W = zeros(size(A));
W(sub2ind(size(A),repmat((1:size(A,1)).',...
1,2),idx)) = v
If you're using older version:
max_values = 2;
[v,idx]=sort(A,2,'descend');
W = zeros(size(A));
W(sub2ind(size(A),repmat((1:size(A,1)).',...
1,2),idx(:,1:max_values))) = v(:,1:max_values)
i am using the older version so i tried with the following code:
max_values = 2;
[v,idx]=sort(A,2,'descend');
W = zeros(size(A));
W(sub2ind(size(A),repmat((1:size(A,1)).',...
1,2),idx(:,1:max_values))) = v(:,1:max_values)
It works fine.
I also tried with choosing three values and i tried with the code by changing the max_values =3;
but i am getting error stating Error using sub2ind The subscript vectors must all be of the same size.
Error in (line 20)
W(sub2ind(size(A),repmat((1:size(A,1)).',...
Could you please help me to overcome the error .
I corrected the error.Now i am able to get three maximum values in each row.Thanks for your help.

Sign in to comment.

More Answers (0)

Categories

Tags

Asked:

on 31 Jul 2019

Commented:

on 31 Jul 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!