MATLAB Answers


add numerical array as column or in cell array

Asked by Paul
on 23 Nov 2012
Latest activity Commented on by Trung Hieu Le
on 10 Jun 2016

How to add a numerical array

 a=[1 2 3 4]

as row into my cell

 C = |'a' 'b' 'c' 'd'|
     |'e' 'f' 'g' 'h'|
     |'i' 'j' 'k' 'l'|
     |'m' 'n' 'o' 'p'|

so, that

 C = |'1' '2' '3' '4'|
     |'a' 'b' 'c' 'd'|
     |'e' 'f' 'g' 'h'|
     |'i' 'j' 'k' 'l'|
     |'m' 'n' 'o' 'p'|

or as new column into cell C:

C = |'1' 'a' 'b' 'c' 'd'|
    |'2' 'e' 'f' 'g' 'h'|
    |'3' 'i' 'j' 'k' 'l'|
    |'4' 'm' 'n' 'o' 'p'|

(the numerical values become strings).

AND: How to transform for example a 2x4 cell into a 1x8 (or 8x1) cell:

 C= |'a' 'b' 'c' 'd'|       ----> C = |'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h'|
    |'e' 'f' 'g' 'h'|   
                         or:----> C = |'a'|

I can solve these problems with for-loops, but imagine you have a huge size of the cell array, it is not very efficient. Is there an easier way? Thanks!


2 Answers

Answer by Jan Simon
on 23 Nov 2012
Edited by Jan Simon
on 23 Nov 2012
 Accepted answer

C = {'a' 'b' 'c' 'd'; ...
     'e' 'f' 'g' 'h'; ...
     'i' 'j' 'k' 'l'; ...
     'm' 'n' 'o' 'p'};
a     = [1 2 3 4];
tmp   = sprintf('%g*', a);
tmp(end) = [];
aC    = regexp(tmp, '*', 'split');
C_row = cat(1, aC,  C);  % Insert as row
C_col = cat(2, aC', C);  % Insert as column
C2 = reshape(transpose(C), 1, [])
C3 = reshape(C, [], 1)


Answer by Azzi Abdelmalek
on 23 Nov 2012
Edited by Azzi Abdelmalek
on 23 Nov 2012

 C = {'a' 'b' 'c' 'd'
      'e' 'f' 'g' 'h'
      'i' 'j' 'k' 'l'
      'm' 'n' 'o' 'p'}
 a=[1 2 3 4]
 out=[num2cell(a); C]


 out=[num2cell(a')  C]

% for third case





Jan Simon
on 23 Nov 2012

@Azzi: Paul asked for "the numerical values become strings", but NUM2CELL replies {1,2,3,4} instead of the wanted {'1', '2', '3', '4'}.

Ok Simon,

outv=[arrayfun(@(x) cellstr(num2str(x)),a); C]


outh=[arrayfun(@(x) cellstr(num2str(x)),a)'  C]

It works well. Thanks a lot

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!