Tak
Tak

Reputation: 3616

Add string headers to double columns Matlab

I have a double matrix A of size 10x10. What I want to do is I have a string array of size 1x10. I want to replace the first row in matrix A with this array of strings to be the headers of these columns. Same with the first column. If anyone could please advise how this can be done in Matlab.

Upvotes: 2

Views: 1387

Answers (1)

rayryeng
rayryeng

Reputation: 104565

For MATLAB R2013b or higher

If you have at least MATLAB R2013b or higher, you can use the array2table function to present the values in your desired format. Let's assume that your matrix is stored in A. Next, assuming your row headers are in a cell array and stored in row and your column headers are stored in a cell array called col, try this:

Try this:

T = array2table(A, 'RowNames', row, 'VariableNames', col);

Here's an example:

>> A = [1 12 30.48; 2 24 60.96; 3 36 91.44]
>> col = {'Feet', 'Inches', 'Centimeters'};
>> row = {'Number 1', 'Number 2', 'Number 3'};
>> T = array2table(A, 'RowNames', row, 'VariableNames', col)

T = 

            Feet    Inches    Centimeters
            ____    ______    ___________

 Number 1     1       12        30.48      
 Number 2     2       24        60.96      
 Number 3     3       36        91.44   

For MATLAB R2013a or lower

If you have R2013a or lower, you have no choice but to use a cell array for this. You can only achieve mixed data types in a matrix with a cell array. What you'll need to do is convert each number into an individual cell in a cell array. I'm going to introduce you to an undocumented function: sprintfc. You are able to print matrices directly to cell arrays.

Therefore, try doing this, assuming that row contains your strings in a cell array for the row header of size 1 x N and col contains your strings in a cell array for the column header of size 1 x N. With your matrix A:

Acell = sprintfc('%f', A); %// Convert matrix to cells
out = [' ', row; col.', Acell]; %// Generate final matrix

out contains your desired matrix. Here's an example:

>> A = [1 12 30.48; 2 24 60.96; 3 36 91.44];
>> Acell = sprintfc('%f', A);
>> row = {'Feet', 'Inches', 'Centimeters'};
>> col = {'Number 1', 'Number 2', 'Number 3'};
>> out = [' ', row; col.', Acell]

out = 

    ' '              'Feet'        'Inches'       'Centimeters' 
    'Number 1'       '1.000000'    '12.000000'    '30.480000'
    'Number 2'       '2.000000'    '24.000000'    '60.960000'
    'Number 3'       '3.000000'    '36.000000'    '91.440000'

Upvotes: 2

Related Questions