write a MatLab function, Shuffle(v), that takes in a vector and outputs a shuffl
ID: 3642720 • Letter: W
Question
write a MatLab function, Shuffle(v), that takes in a vector and outputs a shuffled version of the vector based on the following rules:Switch the first and last elements of the vector
Switch the first two elements with the last two elements of the vector
Switch the first and second elements only if the first element is larger than the second element
Example: if v = [4 8 2 1], then Shuffle(v) will produce [2 4 1 8]
if v = [1 7 -2 3 5], then Shuffle(v) will produce [1 3 -2 5 7]
Explanation / Answer
===== begin Shuffle.m ===== function V = Shuffle( V ) %Shuffle returns shuffle version of the passed vector % Switch the first and last elements of the vector tmp = V(1); V(1) = V(length(V)); V(length(V)) = tmp; % Switch the first two elements with the last two elements of the vector tmp = V(1); V(1) = V(length(V)-1); V(length(V)-1) = tmp; tmp = V(2); V(2) = V(length(V)); V(length(V)) = tmp; % Switch the first and second elements only if the first element is larger than the second element if (V(1) > V(2)); tmp = V(1); V(1) = V(2); V(2) = tmp; end; end % Shuffle ===== end Shuffle.m ===== ===== Sample Output ===== >> V = [4, 8, 2, 1] V = 4 8 2 1 >> Shuffle(V) ans = 2 4 1 8 >> V = [1 7 -2 3 5] V = 1 7 -2 3 5 >> Shuffle(V) ans = 1 3 -2 5 7 >>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.