MATLAB Answers

How do I switch location of the largest and smallest elements of an array?

1 view (last 30 days)
Sharrafa Khan
Sharrafa Khan on 17 Sep 2021
Commented: Chunru on 17 Sep 2021
vect = randi(20,1,15)
vect = 1×15
19 10 1 7 13 10 7 6 20 4 10 2 8 13 14
partA = round(vect)
partA = 1×15
19 10 1 7 13 10 7 6 20 4 10 2 8 13 14
partB=min(partA)
partB = 1
partC=max(partA)
partC = 20
MeanValue=mean(vect)
MeanValue = 9.6000
ind = find(partA~=MeanValue)
ind = 1×15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
partD=ind
partD = 1×15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
partE=sort(partA,'descend')
partE = 1×15
20 19 14 13 13 10 10 10 8 7 7 6 4 2 1
Now how do I switch largest and smallest element of partE?

Answers (1)

Chunru
Chunru on 17 Sep 2021
vect = randi(20,1,15)
vect = 1×15
10 17 7 13 16 14 12 20 9 2 20 5 2 14 10
[~, imax] = max(vect)
imax = 8
[~, imin] = min(vect)
imin = 10
% swap
tmp = vect(imax);
vect(imax) = vect(imin);
vect(imin) = tmp;
vect
vect = 1×15
10 17 7 13 16 14 12 2 9 20 20 5 2 14 10
  2 Comments
Chunru
Chunru on 17 Sep 2021
Do you mean this?
vect_new = vect; % copy the vector to a new one
tmp = vect_new(imax);
vect_new(imax) = vect_new(imin);
vect_new(imin) = tmp;

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by