How to re-order a vector efficiently? The numbers represent 'frames' in a movie that are sorted in the following order:
a=[1 4 7 2 5 8 3 6 9];
the result should be a cell array with the different streams starting with 1,2 and 3:
b{1}=[1 2 3];
b{2}=[4 5 6];
b{3}=[7 8 9];
Right now I'm using a for
loop, but I have a hunch it could be done more efficiently (i.e. less lines of code, less time to run) than a for
loop:
for ind=1:3
b{ind}=a(ind:3:end);
end
The final code has ind=1:30000
instead of ind=1:3
; is there a more efficient way to do this?
Reshape a
to the required shape and use matrix indexing to access its relevant rows.
bmat = reshape(a,k,[]); %k equals 3 in your example
%bmat(1,:) will be your b{1}, bmat(2,:) --> b{2}, and so on.
If you really need to convert it to a cell like in your question then use mat2cell
as follows:
b = mat2cell(bmat, ones(k,1));