For loop problem involving switching numbers in a vector..

I need help switching numbers in a vector in a for loop. x = [1 -2 3 5 4 2]; Compare the 1st and 2nd entries in x. Swap the two entries if the first entry is larger than the second. then do 2nd and 3rd. 3rd and 4th. 4th and 5th. 5th and 6th. then i will need to output the correct final vector.

1 Comment

Please be more specific about the parts you are having difficulty with. Are you able to write "for loops"? Are you familiar with "if" ? Are you able to index values?

Sign in to comment.

 Accepted Answer

Braydon - this seems relatively straight forward. Use the for loop and start iterating from two (the second index) and go through to the length of the vector. At each iteration, compare the kth element with the (k-1)th element. If the latter than the former, then swap the two entries. Since this is a homework question, the easy part is just
x = [1 -2 3 5 4 2];
for k=2:length(x)
% compare the kth and (k-1)th elements
% swap if necessary
end
You just need to fill in the code for eacf of the above two comments.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!