Reputation: 67
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
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