The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Sorting problem
Replies: 6   Last Post: Aug 15, 1996 6:18 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Hans Olsson

Posts: 14
Registered: 12/7/04
Re: Sorting problem
Posted: Aug 14, 1996 4:48 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

In article <>,
Mark Smart <> wrote:
>Does anyone have experience with the following problem? I have
>a matrix of geometric positions
>[x1 y1 z1;
>x2 y2 z2;] etc
>I wish to sort it in the following way:
>1. Firstly according to vector magnitude. This is easy:
>2. Then all vectors of the same magnitude must be sorted with
>respect to x, then y, then z. For example, if
>[1 0 0;
>2 1 0;
>1 3 1;
>0 0 1];
>the first sort produces
>1 0 1; % magn =sqrt(2)
>0 1 1; % =sqrt(2)
>1 1 0; % magn =sqrt(2)
>2 1 0; % =sqrt(5)
>1 3 1;] % =sqrt(11)
>whilst the final output should be
>0 1 1;
>1 0 1;
>1 1 0;
>2 1 0;
>1 3 1;]
>Is there an efficient way of doing this? It may be trivial but
>I've racked my brains and can't think of a solution without many
>for-next loops.

I'm not sure that this is the most effient solution in matlab, but
the problem seems to be to sort vector with respect to x then y then z.
Provided that sort is stable (I believe it is, but I'm not sure)
you could use something like this for that part:
(Forward radix sort is more fun, but it would be a bit longer but

function A=sortmulti(A)
% Radix sort. Stupid but at least vectorized.
for i=size(A,2):-1:1

Main routine could be as complex as:

% Find sequences of several identical magnitudes

% Handle each sequence at a time.
for i=1:length(Istart)

Or as simple as:


So you only need 1 for-loop provided that sort really is stable
(i.e. preserves the order of items with identical keys).

// [Please no junk e-mail]

Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.