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?

 Akzeptierte Antwort

Torsten
Torsten am 12 Jun. 2015

1 Stimme

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

3 Kommentare

Prakriti Sardana
Prakriti Sardana am 12 Jun. 2015
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.
Torsten
Torsten am 12 Jun. 2015
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.
Stephen23
Stephen23 am 12 Jun. 2015
Without any loops:
Azzi Abdelmalek's solution is simpler.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Azzi Abdelmalek
Azzi Abdelmalek am 12 Jun. 2015

1 Stimme

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

3 Kommentare

Prakriti Sardana
Prakriti Sardana am 12 Jun. 2015
Ah! This does not work in the 'for loop' command.
Stephen23
Stephen23 am 12 Jun. 2015
@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.
Prakriti Sardana
Prakriti Sardana am 12 Jun. 2015
Bearbeitet: Prakriti Sardana am 12 Jun. 2015
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by