Hi guys how can swap the max value and min value for a matrix ?
7 views (last 30 days)
Show older comments
I want to swap max and min value to any matrix
9 Comments
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
0 Comments
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
0 Comments
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
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!