splitting an array into unequal parts without loop
9 views (last 30 days)
Show older comments
Kaushik Lakshminarasimhan
on 8 Nov 2017
Commented: Star Strider
on 8 Nov 2017
Given:
v_in = rand(1,100); % length = 100
n = [10 20 10 10 15 25 10]; % length = 7
I want to cut the array v_in into 7 unequal parts, with the length of each part given by the elements in n. Is there a way to accomplish it without using a for loop like this one?
for i=1:length(n)
v_out{i} = v_in(1:n(i)); % move
v_in(1:n(i)) = []; % remove
end
0 Comments
Accepted Answer
Star Strider
on 8 Nov 2017
Use the mat2cell function:
v_in = rand(1,100); % length = 100
n = [10 20 10 10 15 25 10]; % length = 7
Out = mat2cell(v_in, 1, n);
2 Comments
Star Strider
on 8 Nov 2017
As always, my pleasure!
The mat2cell function (and the related num2cell function that won’t work here) are quite useful. (I apologise for it that you had problems with it before. Like everything else, it takes some experimentation with it to understand it.) The key to using it is that the vector of ‘segments’ with respect to every dimension has to sum to that dimension. So here, 1 are the number of rows, and ‘n’ sums to the column size of your vector. If you had a matrix instead of a vector, the ‘segments’ along the rows would have to sum to the row size. If ‘m’ were the number of rows, either ‘m’ or a vector that sums to ‘m’ would work. (The ones function can be extremely useful in this regard, if you want to separate individual rows or columns.)
Use cell2mat with each individual cell array it produces to calculate with them numerically.
More Answers (0)
See Also
Categories
Find more on Multidimensional Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!