Swapping values within a vector if the one after it is greater than the one before it.
2 views (last 30 days)
Show older comments
Need help on some homework that I feel so close yet so far away on.
For example the 1st and 2nd entries in x. I need to swap the two entries if the first entry is larger than the second. and display what the final x-vector looks like.
x = [1 -2 3 5 4 2]
for k = 1:5;
if x(k) > x(k+1)
x(k) = x(k+1)
elseif x(k) < x(k+1)
x(k) = x(k)
end
I haven't yet tried to display the final vector. However when I run this code it gives me some funky numbers. I don't know how to fix it, any suggestions?
0 Comments
Answers (2)
James Tursa
on 2 Oct 2015
To do the swap you could just use a two-element index vector. E.g.,
if x(k) > x(k+1)
x([k,k+1]) = x([k+1,k]);
end
1 Comment
Kirby Fears
on 2 Oct 2015
Edited: Kirby Fears
on 2 Oct 2015
First off, what you're doing isn't a swap. You're overwriting x(k) but what about x(k+1)? It's still retaining it's original value. Also, your else case doesn't do anything. This would be an iterative swap:
x = [1 -2 3 5 4 2];
for k = 1:numel(x)-1;
if x(k) > x(k+1),
temp = x(k);
x(k) = x(k+1);
x(k+1) = temp;
end
end
If your end goal is to sort X in increasing order, you could simply use the sort command...
x = [1 -2 3 5 4 2];
sort(x)
ans =
-2 1 2 3 4 5
Hope this helps.
0 Comments
See Also
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!