How do I convert a vector into an Nx1 cell array of varying-length vectors?

Preface: I'm very new to this. Haven't touched matlab since one semester of college about 20 years ago.
I have a vector of numbers, say:
[1 2 3 4 5 6 7 8 9 10]
I want to create a Nx1 cell array out of that vector where each cell contains a vector and there are up to three elements per vector. Something like this:
{[1 2 3]}
{[4 5 6]}
{[7 8 9]}
{[0]}
I cannot figure out the magic combination of reshape/etc that will achieve this. reshape, for starters, seems to puke because the number of elements in the source vector doesn't exactly match the number that would be in the rows if all rows were of the same length.
I've read the docs on reshape but I don't find the examples to be very helpful. Any help would be appreciated.

 Accepted Answer

A = [1 2 3 4 5 6 7 8 9 0];
% sizes = [3 3 3 1];
nA = numel(A);
% get as many groups of size 3 as you can from A:
sizes = 3*ones(1,floor(nA/3));
% any remaining elements go into an additional group of size up to 2:
remainder = rem(nA,3);
if remainder > 0
sizes(end+1) = remainder;
end
disp(sizes);
3 3 3 1
% partition A into subsets of those respective sizes:
end_idx = cumsum(sizes);
start_idx = [1 end_idx(1:end-1)+1];
C = arrayfun(@(x,y)A(x:y),start_idx,end_idx,'UniformOutput',false).'
C = 4×1 cell array
{[1 2 3]} {[4 5 6]} {[7 8 9]} {[ 0]}

2 Comments

This took me a while to unpack because of several functions and concepts I wasn't familiar with. But after some tinkering, I get it and it makes perfect sense. Thanks for the help!
I'm glad it makes sense - You're welcome!

Sign in to comment.

More Answers (2)

Use mat2cell (with a transpose call if you need an N-by-1 instead of a 1-by-N.)
V = [1 2 3 4 5 6 7 8 9 10]
V = 1×10
1 2 3 4 5 6 7 8 9 10
R = mat2cell(V, 1, [3 3 3 1])
R = 1×4 cell array
{[1 2 3]} {[4 5 6]} {[7 8 9]} {[10]}
C = R.'
C = 4×1 cell array
{[1 2 3]} {[4 5 6]} {[7 8 9]} {[ 10]}
Simpler:
V = [1,2,3,4,5,6,7,8,9,10];
N = 3;
L = numel(V);
S = N*ones(1,ceil(L/N));
S(end) = 1+rem(L-1,N);
C = mat2cell(V,1,S)
C = 1×4 cell array
{[1 2 3]} {[4 5 6]} {[7 8 9]} {[10]}

Products

Asked:

on 6 Apr 2022

Answered:

on 7 Apr 2022

Community Treasure Hunt

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

Start Hunting!