Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Arranging even and odd numbers

Subject: Arranging even and odd numbers

From: xplore29

Date: 21 Feb, 2013 03:52:07

Message: 1 of 2

I have a vector
x=[0 1 2 3 4 5 6 7]
and I want to creat x' from x such that
x'=[0 2 4 6 1 3 5 7]
This can be achieved by following transformation
A*x=x'

where

A=[1 0 0 0 0 0 0 0;
     0 0 1 0 0 0 0 0;
     0 0 0 0 1 0 0 0;
     0 0 0 0 0 0 1 0;
     0 1 0 0 0 0 0 0;
     0 0 0 1 0 0 0 0;
     0 0 0 0 0 1 0 0;
     0 0 0 0 0 0 0 1]

How can I generate matrix A without getting into for loops.

Subject: Arranging even and odd numbers

From: William Frane

Date: 22 Feb, 2013 20:52:06

Message: 2 of 2

If I understand your use case correctly, you can employ MATLAB's matrix indexing ability (see http://www.mathworks.com/company/newsletters/articles/Matrix-Indexing-in-MATLAB/matrix.html) instead of generating a transformation matrix.

For example, if this is your input vector:
a = [0 1 2 3 4 5 6 7]
and your "sort vector" is:
s = [0 2 4 6 1 3 5 7]
(meaning generate the output vector such that it contains element 0 of the input vector at position 0, element 2 of the input at position 1, element 4 of the input at position 2, etc.)
you can simply use matrix indexing to produce your desired output:
b = a(s+1);
(The "+1" is required because MATLAB uses 1-based matrix indexing; alternatively, number the indices in your sort vector from 1 to N rather than from 0 to N-1.)

For example (this is a general case; the even/odd indices case is covered below):
a = [0 4 2 3 1]
s = [1 5 3 4 2]
b = a(s) produces b = [0 1 2 3 4]

Since it appears that you want all the even-indexed entries in the first half of your result and the odd-indexed ones in the second half, your sort vector could be generated as follows (using MATLAB's 1-based indexing):
s = [2:2:numel(a) 1:2:numel(a)]

Hope that helps.

Will

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us