MATLAB: How to use XLSWRITE to add row and column labels to the MATLAB matrix when I write it to Excel in MATLAB 7.3 (R2006b)

MATLAB

I am using XLSWRITE to write numeric data to Excel. I would like to include text row and column headers to the matrix when I write it to Excel.

Best Answer

The following examples illustrate how to use XLSWRITE to add column and row labels to a MATLAB matrix that is written to an Excel file. This can be done either by writing to several sections of the worksheet (Case 1), or by joining the data and labels before writing to the XLS-file (Case 2).
Case 1. Using several XLSWRITE commands:
data=ones(10,4); %Sample 2-dimensional data

col_header={'Temperature','Pressure','X','Y'}; %Row cell array (for column labels)

row_header(1:10,1)={'Time'}; %Column cell array (for row labels)

xlswrite('My_file.xls',data,'Sheet1','B2'); %Write data
xlswrite('My_file.xls',col_header,'Sheet1','B1'); %Write column header
xlswrite('My_file.xls',row_header,'Sheet1','A2'); %Write row header
Case 2. Using one XLSWRITE command:
data=ones(10,4); %Sample 2-dimensional data
data_cells=num2cell(data); %Convert data to cell array
col_header={'Temperature','Pressure','X','Y'}; %Row cell array (for column labels)
row_header(1:10,1)={'Time'}; %Column cell array (for row labels)
output_matrix=[{' '} col_header; row_header data_cells]; %Join cell arrays
xlswrite('My_file.xls',output_matrix); %Write data and both headers