splitting an array into unequal parts without loop
9 ビュー (過去 30 日間)
古いコメントを表示
Kaushik Lakshminarasimhan
2017 年 11 月 8 日
コメント済み: Star Strider
2017 年 11 月 8 日
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 件のコメント
採用された回答
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 件のコメント
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 Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!