splitting an array into unequal parts without loop
조회 수: 2 (최근 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
댓글 수: 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에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!