簡體   English   中英

如何使用Matlab在excel中查找最后一個列索引

[英]How to find the last column index in excel with Matlab

我正在使用Matlab將數據作為矩陣寫入excel文件。 我的矩陣尺寸各不相同,我事先也不知道矩陣的尺寸。 假設我有各種尺寸的矩陣A,B和C。 我想做的是先將矩陣A寫入excel,然后在矩陣A之后以1列的間隙寫入矩陣B。 我不知道Matlab是否可以在excel中找到最后一個列索引,並在這兩個矩陣之間創建間隙。

我的代碼現在是這樣的:

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 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列)。 例如,要顯示它可以處理字母增量,可以運行簡短測試:

>> 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寫入矩陣A 要知道從哪里開始矩陣B ,只需計算A的大小並添加必要的間隔即可。 假設您的矩陣A有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)

如果矩陣很大(以列數為單位),則在調用xlswrite之前,最好先進行檢查以確保您不會用完列,這是明智的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”列找到兩個位置。

另外,我不記得是否length(A)或size(A)的哪個元素引用了A中的列數。如果length(A)沒有給您正確的列數,請與另一列一起玩。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM