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

3 views (last 30 days)
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
Sharrafa Khan
Sharrafa Khan on 17 Sep 2021
Okay thanks! But can I make a new vector by switching the largest and smallest value of partE?
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.

Categories

Find more on Creating and Concatenating Matrices 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!