Increase the number of elements inside a cell

3 次查看(过去 30 天)
Hi. I have this cell:
A = {'5';'11'};
B = {'7';'19'};
out = [A,B]; % cell 2x2
I should go from an 'out' cell 2x2 to an 'out' cell 2x4, where the missing columns (columns 3 and 4) are null cells:
empty_cell = cell(2,1);
The total number of columns in the 'out' cell should be imposed by:
parameter = 4;
So, the end result I want to get must be this:
empty_cell = cell(2,1);
out = [A,B,empty_cell,empty_cell]; % cell becoming 2x4 (where 4 is 'parameter')

采纳的回答

Stephen23
Stephen23 2023-6-24
No loop, no concatenation required:
A = {'5';'11'};
B = {'7';'19'};
out = [A,B]; % cell 2x2
parameter = 4;
out(:,end+1:parameter) = {[]}
out = 2×4 cell array
{'5' } {'7' } {0×0 double} {0×0 double} {'11'} {'19'} {0×0 double} {0×0 double}

更多回答(1 个)

Deep
Deep 2023-6-24
You can simply add empty columns in a loop.
Given out and parameter are defined (out can be a cell of any shape, need not be 2x2),
% Calculate the number of empty columns to be added
num_empty_cols = parameter - size(out, 2);
Then, create an empty cell array with the same number of rows as 'out'
empty_cell = cell(size(out, 1), 1);
Finally add these cells in a simple loop:
for k = 1:num_empty_cols
out = [out, empty_cell];
end
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by