Reputation: 1637
I have a vector of numbers and I want to store the every four elements into a cell. So the first 4 elements will go into the first cell, the next four elements will go into the second cell and so on.
Is there a way to do this without using loops? Thanks!
Upvotes: 0
Views: 67
Reputation: 65460
You could use mat2cell
to do this
data = 1:16;
output = mat2cell(data, 1, (numel(data)/4) * ones(1,4))
% output{1} =
%
% 1 2 3 4
%
% output{2} =
%
% 5 6 7 8
%
% output{3} =
%
% 9 10 11 12
%
% output{4} =
%
% 13 14 15 16
Personally I find the input format a little confusing. Another approach would be to reshape your matrix to have 4 rows and then use num2cell
to break each column into it's own cell.
data = 1:16;
output = num2cell(reshape(data, 4, []), 1)
Upvotes: 1