Swapping values within a vector if the one after it is greater than the one before it.
Ältere Kommentare anzeigen
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?
Antworten (2)
James Tursa
am 2 Okt. 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 Kommentar
Stephen23
am 3 Okt. 2015
This is the more efficient solution for swapping two values.
Kirby Fears
am 2 Okt. 2015
Bearbeitet: Kirby Fears
am 2 Okt. 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.
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!