Reputation: 3239
I have an array
a = [1 2 3 4 5 6 7 8]
I want to get every group of 4 so the result is as such
[1 2 3 4]
[5 6 7 8]
I do not know how many elements there will be but I know it is divisible by 4
so something like a(1:4) and a(5:8) wont work, I can use a loop, but is there a way to not use a loop?
Upvotes: 0
Views: 546
Reputation: 2802
For an unknown number of elements in a
you can use reshape
you just need to figure out how many rows you will have in the final matrix or (better for your case) the number of columns.
a = 1:4*10;
a2 = reshape(a, 4, []).';
If you went the rows routine you would do this.
a = 1:4*10;
a2 = reshape(a, [], numel(a) / 4).';
You just need to be sure that a
has the proper number of elements. numel
simply tells you the total element count.
Upvotes: 1