Hi guys how can swap the max value and min value for a matrix ?
Show older comments
I want to swap max and min value to any matrix
9 Comments
Guillaume
on 16 Dec 2018
What should be done if there are several elements that are equal to the max or the min?
Ali Mohammad
on 16 Dec 2018
Rik
on 16 Dec 2018
This sounds a lot like homework. Is it?
Ali Mohammad
on 16 Dec 2018
Edited: Ali Mohammad
on 16 Dec 2018
John D'Errico
on 16 Dec 2018
Edited: John D'Errico
on 16 Dec 2018
Can you find the max value? (help max)
Can you find the min value? (help min)
Or, can you use the sort function? Why not read the help?
So come on. Make an effort. This is your homework, not ours. There must be a zillion ways to do this.
Ali Mohammad
on 17 Dec 2018
madhan ravi
on 17 Dec 2018
upload your code
Mark Sherstan
on 17 Dec 2018
Post your code so we can direct you.
Ali Mohammad
on 17 Dec 2018
Edited: Ali Mohammad
on 17 Dec 2018
Answers (3)
madhan ravi
on 17 Dec 2018
No loops needed:
A=[1 2 3; 4 5 6;4 7 8]
[value,idx]=max(A(:))
[val,iddx]=min(A(:))
A(idx)=val;
A(iddx)=value
Stephen23
on 17 Dec 2018
>> A = randperm(9)
A =
5 6 1 3 7 8 4 9 2
>> [~,idx] = max(A(:));
>> [~,idn] = min(A(:));
>> A([idx,idn]) = A([idn,idx])
A =
5 6 9 3 7 8 4 1 2
Image Analyst
on 17 Dec 2018
I suggest you use my vectorized method using min(), max(), and find(). The other solutions I've seen so far will not work in the general situation where your max or min occurs more than once since min() and max() do not (for some weird reason) return ALL indexes):
A = [1 1 3 4 9 9 ; 4 1 1 4 9 9] % Max and min occur in multiple places.
minValue = min(A(:))
maxValue = max(A(:))
minIndexes = find(A == minValue)
maxIndexes = find(A == maxValue)
A(minIndexes) = maxValue;
A(maxIndexes) = minValue
Categories
Find more on Matrix Indexing 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!