Elijah
Elijah

Reputation: 67

Split array into pieces in MATLAB

I woutld like to split an array into equal pieces like this:

 a=[1 2 3 4 5 6 7 8 9 10]
 n = 2;
 b = split(a, n);

 b =

 1     2     3     4     5
 6     7     8     9    10

Which function can do this?

Upvotes: 5

Views: 30582

Answers (2)

yuk
yuk

Reputation: 19870

If a can be divided by n you can actually provide only one argument to RESHAPE.

To reshape to 2 rows:

b = reshape(a,2,[])

To reshape to 2 columns:

b = reshape(a,[],2)

Note that reshape works by columns, it fills the 1st column first, then 2nd, and so on. To get the desired output you have to reshape into 2 columns and then transpose the result.

b = reshape(a,[],2)'

You can place a check before reshape:

assert(mod(numel(a),n)==0,'a does not divide to n')

Upvotes: 13

Ze Ji
Ze Ji

Reputation: 196

Try this:

a = [1 2 3 4 5 6]
reshape (a, 2, 3)

Upvotes: 14

Related Questions