Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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?

Antworten (1)

Chunru
Chunru am 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 Kommentare
Sharrafa Khan
Sharrafa Khan am 17 Sep. 2021
Okay thanks! But can I make a new vector by switching the largest and smallest value of partE?
Chunru
Chunru am 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;

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by