Matlab可读缓慢循环

时间:2016-02-09 14:14:13

标签: excel performance matlab loops activex

我有一个循环,它读取xls工作簿的几个选项卡(由optionsList选择)。运行需要很长时间。我不确定是不是因为它是为每个循环打开和关闭excel actxserver?代码如下:

    for ii=1:length(optionsList);

        optionsTables.(optionsList{ii})=readtable(inputFile,'Sheet', optionsList{ii},'ReadRowNames',true);


    end

我有什么选择来优化它?

我试过了:

Excel = actxserver ('Excel.Application'); 
if ~exist(inputFile,'file') 
    ExcelWorkbook = Excel.Workbooks.Add; 
    ExcelWorkbook.SaveAs(inputFile,1); 
    ExcelWorkbook.Close(false); 
end 
Excel.Workbooks.Open(inputFile); 
tic
for ii=1:length(optionsList);

    optionsTables.(optionsList{ii})=readtable(inputFile,'Sheet', optionsList{ii},'ReadRowNames',true);

end
Excel.ActiveWorkbook.Save; 
Excel.Quit 
Excel.delete 
clear Excel

toc

这不会缩短运行时间

Profile results attached

1 个答案:

答案 0 :(得分:2)

正如评论中所述,readtable在内部调用xlsread来读取Excel数据。它有点像兔子洞(readtable),但你可以在剖析器中看到它。虽然它也使用ActiveX来提高速度,但它会为每次调用设置和销毁此接口。通过反复呼叫,这通常会导致重大的浪费。 CPU时间。

一种可能的替代方法是利用单个ActiveX连接并使用循环读取每个工作表,然后转换为表格。这似乎是您尝试使用% Generate sample data file, lazy approach A = rand(10); for ii = 1:10 sheetname = sprintf('Tab_%u', ii); xlswrite('asdf.xlsx', A, sheetname); end % Set up import parameters optionsList = {'Tab_1', 'Tab_3', 'Tab_5', 'Tab_7', 'Tab_10'}; % Use single ActiveX instance to read in desired data exl = actxserver('excel.application'); exlWkbk = exl.Workbooks; exlFile = exlWkbk.Open(fullfile(cd, 'asdf.xlsx')); % Read the data from the sheet, then convert to table for ii = 1:length(optionsList) currentSheet = exlFile.Sheets.Item(optionsList{ii}); optionsTables.(optionsList{ii}) = cell2table(currentSheet.UsedRange.Value); end % Clean up exlFile.Close(false); exl.Quit(); exl.delete(); clear exl 的第二个示例。

这种方法的一个例子:

optionsTables = 

     Tab_1: [10x10 table]
     Tab_3: [10x10 table]
     Tab_5: [10x10 table]
     Tab_7: [10x10 table]
    Tab_10: [10x10 table]

返回:

@JsonAnyGetter

我还没有机会针对其他方法对此进行基准测试,但更快。

相关问题