如何在Matlab中findexcel中的最后一列索引

我正在使用Matlab将数据作为matrix写入excel文件。 我的matrix的维度各不相同,我不知道matrix的维度。 假设我有不同维度的matrixA,B和C. 我想要做的是首先写入matrixA到Excel中,然后在A之后写入matrixB,其间有1列间隔。 我不知道是否有一种方法可以findExcel中的最后一个列索引,并创build这两个matrix之间的差距。

我的代码现在是这样的:

xlswrite('My file.xls',A,'My Sheet','B2'); %% Here is what I don't know to fill in to find the starting range index for my next matrix. %% xlswrite('My file.xls',B,'My Sheet','newindex'); 

要根据索引号计算Excel列ID,我做了以下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 

这将适用于任何数字,但请注意,Excel的列数最多(在我的版本中最多为2^14=16384列)。 例如,为了显示它处理字母增量,可以运行简短testing:

 >> 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 

所以在你的情况下,你开始在列'B...' ,这是列索引2写你的matrixA 要知道从哪里开始matrixB ,只需计算A的大小并添加必要的间隙。 假设你的matrixA有573列。

 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) 

如果您的matrix非常大(以列数为单位),在您调用xlswrite之前包含一个检查以确保您不会用尽列

你可以尝试像这样:

 cellVector= ['A2';'B2';'C2';'D2';'E2']; %...etc as many as you need cellstart = 'B2'; cellVectorLoc = find(cellVector == cellstart(1)); % Finds where B is located in cellVector xlswrite('My file.xls',A,'My Sheet',cellstart); nextCellLoc = length(A) + cellVectorLoc + 1; % length of A plus location in index + 1 for blank column. I can't remember if you should use length() or size(). newIndex= cellVector(nextCellLoc,:); % new index xlswrite('My file.xls',B,'My Sheet',newindex); 

请注意,这对列Z后的单元格不起作用,例如, cellVectorLoc = find(cellVector == cellstart(1)); 将在cellVector中为“AA”列find两个位置。

此外,我不记得是否长度(A)或大小(A)的哪个元素指的是列中的A的数量。如果长度(A)没有给出正确的列数。