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?
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.
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.
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.
n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .
Try this:
a = [1 2 3 4 5 6]
reshape (a, 2, 3)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With