removing max of a matrix

Hello
I have a matrix like this
if true
A=[23,43,32,45,76,56,34,65,92,57];
end
now I want to find max and second max of it so after finding max of it, I want to remove it from matrix and then find another max (which would be second max) but I don't know how remove the first one. I use this:
if true
B=A - [x];
end
but it subtract first max from all of matrix elements

 Accepted Answer

Try this:
A=[23,43,32,45,76,56,34,65,92,57, 92, 92, 92, 76]
% Remove max(es) from A
A(A==max(A)) = []
% Determine the second max from A
secondhighestNumber = max(A)
Note, using == lets it remove more than one occurrence of the max, unlike if you had used max() to determine the index of the max.

2 Comments

thank you for this answer, it was a really great helped
If you want to remove any and all highest values, and any and all second highest values, regardless of how many of each there are, simply call the line twice:
A=[23,43,32,45,76,56,34,65,92,57, 92, 92, 92, 76]
% Remove max(es) from A
A(A==max(A)) = [] % Remove the four 92s.
A(A==max(A)) = [] % Remove the two 76s

Sign in to comment.

More Answers (1)

This will remove the two largest elements of ‘A’ and leave the original order unchanged:
[As,idx] = sort(A,'descend');
A(idx([1 2])) = [];
A =
23 43 32 45 56 34 65 57

4 Comments

thanks for your answer, but it's part of a project and I've been told to not use "sort" or I could simply use this:
if true
B=sort (A);
disp (B(9:10))
end
My pleasure.
You did not specify that constraint in your original Question. You also did not mention that this was a homework problem. (We do not provide complete Answers to homework problems.)
Since I already posted a solution, this loop will produce the same result:
B = A;
for k1 = 1:2
[~,idx] = max(B);
B(idx) = [];
end
B % Display Result
The result is the same as previously posted.
MSAA asked to " find another max", not remove it. He also said to "remove the first one" and did not mention removing the second one. So that's why my solution removed any and all max values and found, but did not remove, the second highest value. My solution uses max(), not sort(). Please specify if max() is also not allowed.
thanks for your solution, it was a great help

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!