Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am working on a MATLAB project question. I have to use the switch statement fo

ID: 3587617 • Letter: I

Question

I am working on a MATLAB project question.

I have to use the switch statement for this :
Switch the max and min elements in a vector. For example, assume vec = ceil(rand(1, 10)*100) is a vector containing 10 random generated integers. The script you provide will swap the maximum and the minimum element in the vector. For example, if vec=[ 16    98    96    49    81    15    43    92    80    96], you script will result in vec = [ 16    15  
96    49    81     98   43    92    80    96].

Please help

Explanation / Answer

function vec = switchmaxmin()
% generate 10 random elements
vec = ceil(rand(1, 10)*100);
disp(vec);
% initial minimum and maximum indeces
mxi = 1;
mni = 1;
%initial maximum and mininum elements
mx = vec(1);
mn = vec(1);
for i=2:length(vec)
% find max element and store its index
switch mx<vec(i)
case 1
mx = vec(i);
mxi = i;
end
% find min element and store its index
switch mn > vec(i)
case 1
mn = vec(i);
mni = i;
end
end
  
% swap minumum and maximum elements
temp = vec(mxi);
vec(mxi) = vec(mni);
vec(mni) = temp;
end

disp(switchmaxmin());
% 62 39 17 96 94 30 45 100 42 98
% 62 39 100 96 94 30 45 17 42 98

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote