splitting an array into unequal parts without loop

9 vues (au cours des 30 derniers jours)
Kaushik Lakshminarasimhan
Commenté : Star Strider le 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

Réponse acceptée

Star Strider
Star Strider le 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 commentaires
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 le 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by