splitting an array into unequal parts without loop

10 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2017-11-8
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 个评论
Kaushik Lakshminarasimhan
No wonder I didn't think of this. I decided to stay away from mat2cell after a bad experience a while ago when it took me more than 15 minutes to get it to work. Looks like I should reconsider my position. Thanks!
Star Strider
Star Strider 2017-11-8
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by