Search code examples
arraysmatlabmatrixdoublecell

How to combine numeric and text in an array smartly


I have a numeric array which i wish to combine with a text array.

TX = {'a' 'b' 'c'}
NM = magic(30)

combined = ([TX NM])

How can i manage to get the following new structure out of it:

COMBI = a b c are in columns 1,2,3 and have the same value from row 1:30, first numeric value of NM starts in column 4 and goes until column 33, and has values from row 1:30.

I always get but i want all values in one matrix

'a' 'b' 'c' 30x30 double

but i want

1: 'a'  'b' 'c' 30 columns of double in cell notation, i.e. '3.54' 
2: 'a'  'b' 'c' 30 columns of double in cell notation, i.e. '3.54' 
3: 'a'  'b' 'c' 30 columns of double in cell notation, i.e. '3.54' 
...

30: 'a' 'b' 'c' 30 columns of double in cell notation, i.e. '3.54' 

How can i do that?

UPDATE 1 : thanks Daniel, I updated the example code with ' ' UPDATE 2 : problem solved by constructing an empty array first and pasting numeric or text data inside, thanks Benoit_11 UPDATE 3 : an extra snipped is added to Benoit's great solution by working with unequally sized numeric matrices:

%// To generalize;
n = numel(TX);
NumRowCol = size(NM,1);
NumCol = size(NM,2); % <- the 'new' part considers column size 
%// Initialize the cell
MyCell = cell(NumRowCol,n+NumCol);
%// Insert text in first 3 columns
MyCell(:,1:3) = repmat(TX,NumRowCol,1);
%// Fill the rest with your numeric array in "cell" format.
MyCell(:,n+1:end)= num2cell(NM);
%// Display MyCell
MyCell;

Solution

  • I think you want to do something like the following. I use a numeric array of size 5 x 5 to demonstrate but that's the same idea in your case.

    clear
    clc
    
    TX = {'a' 'b' 'c'};
    NM = magic(5);
    
    %// To generalize;
    n = numel(TX);
    NumRowCol = size(NM,1); %/// Since you use a magic matrix there are as many rows and columns. You might need to update this with different numeric arrays.
    
    %// Initialize the cell
    MyCell = cell(NumRowCol,n+NumRowCol);
    
    %// Insert text in first 3 columns
    MyCell(:,1:3) = repmat(TX,NumRowCol,1);
    
    %// Fill the rest with your numeric array in "cell" format.
    MyCell(:,n+1:end)= num2cell(NM);
    
    %// Display MyCell
    MyCell
    
    
    MyCell = 
    
        'a'    'b'    'c'    [17]    [24]    [ 1]    [ 8]    [15]
        'a'    'b'    'c'    [23]    [ 5]    [ 7]    [14]    [16]
        'a'    'b'    'c'    [ 4]    [ 6]    [13]    [20]    [22]
        'a'    'b'    'c'    [10]    [12]    [19]    [21]    [ 3]
        'a'    'b'    'c'    [11]    [18]    [25]    [ 2]    [ 9]