I need to sort scalars. Is that possible?

My matlab code for a simple program is:
for t=1:length(x)
x1 = x(t+1) - x(t)
end
Now, I need to sort the variable 'x1', which is a scalar, in ascending order. Is that possible?
Or, can I convert my scalar 'x1' into a vector?

 Accepted Answer

for t=1:length(x)
deltax(t) = x(t+1) - x(t)
end
deltax_sort = sort(deltax);
Best wishes
Torsten.

3 Comments

Oh! Thank you very much!
This works.
PS: is the 'delta' command one of the basic commands in MATLAB? Because if it is, it means I was just too lazy/not-focused to have come across it so far.
No, it's just a name for the array of consecutive differences of the vector x.
The answer Azzi gave is even simpler than mine. Here, deltax is directly calculated using diff(x) without the need to use a for-loop.
Best wishes
Torsten.
Without any loops:
Azzi Abdelmalek's solution is simpler.

Sign in to comment.

More Answers (1)

x=[1 2 3 0 5 10 ]
x1=sort(diff(x))

3 Comments

Ah! This does not work in the 'for loop' command.
@Prakriti Sardana: you are correct, it does not work for a loop. Because MATLAB is a high-level language, and often doing basic things in a loop is the slow and awkward way of doing things. To use MATLAB efficiently you need to learn about code vectorization, which is what Azzi Abdelmalek is doing. This is much faster, simpler and less buggy than using loops.
Hm, yes, I can see that Mr Abdelmalek's solution is simpler; however, for my particular code, it's a little more convoluted than this command would work for. Torsten's however, worked well for my purpose. That's all.
True though, before proceeding, I must read MATLAB theory thoroughly.

Sign in to comment.

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!