# Concatenate two cell colums with different length, in Variables window it is possible while horzcat gives "not consistent" error.

4 views (last 30 days)
Csaba on 2 Jul 2020
I have two celll columns.
a={'11';'21';'31'};
b={'12';'22'};
if I issue the
c=[a,b];
command it gives the error
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
However, if I do a
c=a;
and then I go to the Variables window and open 'c' and 'b' variables and copy the first (and only) column of 'b', I can paste the content ANYWHERE in the 'c' correctly. All the other (not involved) cell values become empty. How to reproduce it programmatically???

madhan ravi on 9 Jul 2020
ab = {a, b};
[Val, which_one] = max([numel(a),numel(b)]);
c = cell(Val, 2);
c(:, 1) = a;
c(1 : numel(b), 2) = b
% or perhaps you want
c = cell(5);
c(1:numel(a), 1) = a;
c(end - numel(b) + 1 : end, end) = b

madhan ravi on 2 Jul 2020
c = {a, b} %? if this doesn't do what you want , you need to illustrate with an expected result.

Csaba on 2 Jul 2020
No, it does not do!
c={a,b}
c =
1×2 cell array
{3×1 cell} {2×1 cell}
It makes an 1x2 cell array, instead of e.g. 3x2 cell array. What I want is e.g.
c =
3×2 cell array
{'11'} {'21' }
{'12'} {'22' }
{'13'} {0×0 double}
or
c =
3×2 cell array
{'11'} {0×0 double}
{'12'} {'21' }
{'13'} {'22' }
or, if I paste at - let's say (4,5) field of 'c'
c =
5×5 cell array
{'11' } {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{'12' } {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{'13' } {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{0×0 double} {0×0 double} {0×0 double} {0×0 double} {'21' }
{0×0 double} {0×0 double} {0×0 double} {0×0 double} {'22' }
madhan ravi on 2 Jul 2020
ab = {a, b};
[Val, which_one] = max([numel(a),numel(b)]);
c = cell(Val, 2);
c(:, 1) = a;
c(1 : numel(b), 2) = b
% or perhaps you want
c = cell(5);
c(1:numel(a), 1) = a;
c(end - numel(b) + 1 : end, end) = b
Csaba on 9 Jul 2020
Thanks, although it is a workaround (probably not possible to do it more elegantly) I would accept your answer if you would put it as an answer.