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

I want to swap max and min value to any matrix

9 Comments

What should be done if there are several elements that are equal to the max or the min?
now I need to learn how to swap if there is only 1 max and 1 min
but if you have the answer to all cases that would be very useful too
This sounds a lot like homework. Is it?
Yes it is for homework
new to matlab and programming in general
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.
i know how to find the max value and min value
and I managed to make a loop looking for a max value and min value but I tried to find the way to swap the values and i could'nt that is why I came here for someone to guide me
how could you tell I didn't make any effort ?
Post your code so we can direct you.
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)

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
>> 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
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

Asked:

on 16 Dec 2018

Answered:

on 17 Dec 2018

Community Treasure Hunt

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

Start Hunting!