I am writing data as matrices into excel file using Matlab. My matrices\' dimension varies and I don\'t know the matrices\' dimension in advance. Let\'s say I have matrix A,
To calculate an Excel column ID based on an index number I made the following function:
function col = excel_column(n)
%// find LSB
xlsb = mod(n-1,26)+1 ;
xmsb = fix((n-1)/26) ;
%// find MSB (recursively if necessary)
if xmsb >= 1
col = [excel_column(xmsb) char(xlsb+64)] ;
else
col = char(xlsb+64) ;
end
This will work for any number, but be careful that Excel has a maximum number of column (2^14=16384
columns max in my version). As an example, to shows that it handles the letter incrementation, you can run the short test:
>> x = [25:28 233:236 700:705 16383:16385] ;
for n=x
fprintf('Index: %5d => Column: %s\n', n , excel_column(n) )
end
Index: 25 => Column: Y
Index: 26 => Column: Z
Index: 27 => Column: AA
Index: 28 => Column: AB
Index: 233 => Column: HY
Index: 234 => Column: HZ
Index: 235 => Column: IA
Index: 236 => Column: IB
Index: 700 => Column: ZX
Index: 701 => Column: ZY
Index: 702 => Column: ZZ
Index: 703 => Column: AAA
Index: 704 => Column: AAB
Index: 705 => Column: AAC
Index: 16383 => Column: XFC
Index: 16384 => Column: XFD %// Last real column
Index: 16385 => Column: XFE %// Careful. This column DOES NOT exist in Excel
So in your case, You start to write your matrix A
at column 'B...'
, which is column index 2
.
To know where to start your matrix B
, simply calculate the size of A
and add the necessary gap.
Let's say your matrix A
has 573 columns.
startIdx_A = 2 ; %// Matrix "A" started at column index 2
ncA = size(A,2) ; %// Number of column in A, should return 573
columnGap = 1 ; %// how much gap you want between "A" and "B"
startColumnMatrixB_index = startIdx + ncA + columnGap ; %// index of the first column for Matrix "B"
startColumnMatrixB_excel = excel_column(startColumnMatrixB_index) ; %// return 'VD' (assuming A had 573 columns)
If your matrices are very large (in number of columns), it would be prudent to include a check to make sure you won't run out of column before you call the xlswrite