0

I have the following vector u:

u=[a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4]; 

I want to permute the elements of of u to make the following vector, uNew:

uNew=[a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4]; 

I can think of no way of doing this other than with a for loop:

uNew=[]; for i=1:4 uNew=[uNew,u(i:4:end)]; end 

But I'm hoping that a built-in function exits? Thanks!

2
  • Do you know before hand how many elements separate each vector? For example, do you know that a, b and c are all the same size? In addition, is there a possibility that there are more vectors?... could there be a d? e? Commented Aug 26, 2015 at 19:22
  • No there can't be d, e, etc. so I know everything about the vector. ai, bi and ci are scalars I used to make the concept clearer in the question. Commented Aug 26, 2015 at 19:23

3 Answers 3

3

Reshape it to a matrix which, read column by column, contains the order you want:

n=3 % number of categories (a,b,c) u2=reshape(u,[],n).' 

then convert it back to a vector:

u2=u2(:); 
Sign up to request clarification or add additional context in comments.

3 Comments

Was seriously just about to put this.
@rayryeng: Is there any alternative? ;)
... not that I can think of currently!
2

I'd use Daniel's approach. But just to provide an alternative:

m = 4; %// size of each initial "block" [~, ind] = sort(mod(0:numel(u)-1,m)+1); uNew = u(ind); 

Note that this works because, as per sort's documentation,

The ordering of the elements in B (output) preserves the order of any equal elements in A (input)

Comments

0

Another approach:

N = 4; uNew = u(mod(0:numel(u)-1, N) * N + floor((0:numel(u)-1)/N) + 1); 

1 Comment

Your code as it stands gives me an error. Do you mean u(mod(0:numel(u)-1, numel(u)/N)*N + floor((0:numel(u)-1)/numel(u)*N) + 1)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.