Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into pieces in MATLAB

Tags:

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?

like image 996
Elijah Avatar asked Dec 23 '11 11:12

Elijah


People also ask

How do you split an array in Matlab?

x = A ./ B divides each element of A by the corresponding element of B . The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

How do you split an array into two?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

How do you split data into a group in Matlab?

You can use grouping variables to split data variables into groups. Typically, selecting grouping variables is the first step in the Split-Apply-Combine workflow. You can split data into groups, apply a function to each group, and combine the results.

How do you find the number of elements in an array in Matlab?

n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .


2 Answers

Try this:

a = [1 2 3 4 5 6]
reshape (a, 2, 3)
like image 159
Ze Ji Avatar answered Oct 17 '22 02:10

Ze Ji


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')
like image 40
yuk Avatar answered Oct 17 '22 01:10

yuk