Adamosphere
Adamosphere

Reputation: 77

Matlab: How to re-order (re-organize) a matrix

I have a random column matrix:

r = rand(1,300)';

I want to re-order it so that instead of having elements in the order of 1,2,3,...,300 I will have elements 1,11,21,31,...,291,2,12,22,32,...,292,3,13,33,...293,...,300.

In other words, I want to take every 10th value, beginning with 1 and put them in that order, then do the same for 2 with every 10th value. I know one way to do this is:

n = 10;
r = [r(1:n:numel(r)); r(2:n:numel(r)); r(3:n:numel(r));...;r(10:n:numel(r))];  % Skipped 4-9 in this example

But obviously, this is very cumbersome to do more than a couple of times. Is there something more efficient?

A loop should be easy, but I am not doing it correctly, it seems (I can see why this might not work, but I can't correct it).

(Here is what I tried:)

n = 10;
for i = 1:10
a = [r(i:n:numel(r))];
end

Any suggestions or help is greatly appreciated.

Upvotes: 2

Views: 449

Answers (4)

Rafael Monteiro
Rafael Monteiro

Reputation: 4549

You can do it like this:

r = reshape(reshape(r, 10, 30)', 300, 1)

EDIT:

As pointed out by @LuisMendo on the comments, it's safer to use .' than ' to transpose the matrix, because if the matrix is complex, that could introduce a complex conjugation. Then, it would be safer to do it like this:

r = reshape(reshape(r, 10, 30).', 300, 1)

Upvotes: 4

RoryG
RoryG

Reputation: 1123

Some of the other solutions posted are more efficient, but your idea was a good one. It requires a simple fix to work:

N = numel(r);
M = N/10;
a=[];
for ii = 1:M
        a= [a r(ii:10:N)];
end

Hope this helps

Upvotes: 1

Divakar
Divakar

Reputation: 221514

Try this -

intv = 10; %%// Interval after which you intend to get the values consecutively
out = r(reshape(reshape(1:numel(r),intv,[])',1,[]))

Upvotes: 1

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

You could reshape it into 30x10 matrix, transpose, and take the flat index:

A = 1:300;
A = reshape(A,30,10);
A = A';
A = A(:);

Upvotes: 1

Related Questions