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

조회 수: 3 (최근 30일)
Sharrafa Khan
Sharrafa Khan 2021년 9월 17일
댓글: Chunru 2021년 9월 17일
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?

답변 (1개)

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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by