Hi guys how can swap the max value and min value for a matrix ?

7 views (last 30 days)
I want to swap max and min value to any matrix
  9 Comments
Ali Mohammad
Ali Mohammad on 17 Dec 2018
Edited: Ali Mohammad on 17 Dec 2018
The goal is to program the matlab to swap max and min value in a matrix
clc
clear all
A=[1 2 3; 4 5 6;4 7 8]
c=max(max(A))
g=min(min(A))
for i=1:3
for j=1:3
if A(i,j)==max(max(A))
A(i,j)=g;
end
end
end
for i=1:3
for j=1:3
if A(i,j)==min(min(A))
A(i,j)=c;
end
end
end
A

Sign in to comment.

Answers (3)

madhan ravi
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
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
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 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!