How do I convert a vector into an Nx1 cell array of varying-length vectors?
Show older comments
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
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]
R = mat2cell(V, 1, [3 3 3 1])
C = R.'
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)
Categories
Find more on Time Series Events in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!