How to export data from Matlab to excel for a loop?

后端 未结 3 960
旧时难觅i
旧时难觅i 2021-01-03 15:26

I have a code for \"for loop\"

for i=1:4 statement... y=sim(net, I); end

now

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 16:08

    You can also do for yourself what xlswrite does internally, which is interact using COM. I prefer to do this when I have a frequently used excel template or data file, because it allows for more control (albeit with more lines of code).

    Excel    = actxserver('Excel.Application');
    Workbook = Excel.Workbooks.Open('myExcelFile.xlsx');
    MySheet  = Excel.ActiveWorkBook.Sheets.Item(1);
    
    set( get(MySheet,'Range','A1:A10'), 'Value', yourValues);
    ...
    invoke(Workbook, 'Save');
    invoke(Excel, 'Quit');
    delete(Excel);
    

    This would allow you to save new data to new ranges without re-opening excel each time.

    Even better would be to define an oncleanup function (as does xlswrite) to prevent lost file locks (especially when you're doing things like exiting out of debug mode):

    ...
    myWorkbook = Excel.Workbooks.Open(filename,0,true);
    cleanUp = onCleanup(@()xlsCleanup(Excel, filename));
    
    function xlsCleanup(Excel,filepath)
        try
            Excel.DisplayAlerts = 0; %// Turn off dialog boxes
            [~,n,e] = fileparts(filepath); %// Excel API expects just the filename
            fileName = [n,e];
            Excel.Workbooks.Item(fileName).Close(false);
        end
        Excel.Quit;
     end
    

提交回复
热议问题