Kevin
Kevin

Reputation: 3239

MATLAB - Get every N elements in a vector

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

Answers (1)

Matt
Matt

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

Related Questions