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

一曲冷凌霜 提交于 2019-12-30 05:29:13

问题


I have a code for "for loop"

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

now i need to export the value of y to excel sheet. for that i used..

xlswrite('output_data.xls', y, 'output_data', 'A1')

but my problem is that the ID of excel i.e. "A1" should change according to each iteration... in my case for iteration 1-> A1, iteration-> A2 and so on..

anybody please help me out .. thanks in advance. for any assistance.. or suggestion..


回答1:


You can store sim outputs in a vector (y(ii)) and save in the sheet with a single write. This is also more efficient since you perform a single bulk-write instead of many small writes.

Specify the first cell and y will be written starting from there.

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

xlswrite('output_data.xls', y', 'output_data', 'A1');

If you prefer specify the range write ['A1:A',num2str(last)] instead of A1.

If you really want to write within the loop try:

for ii=1:last
    ...
    y=sim(net, I);
    xlswrite('output_data.xls', y, 'output_data', sprintf('A%d',ii));
end



回答2:


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



回答3:


You can put xlswrite after for loop.You just want to do is save you result in a matrix.This function can write a matrix. also,you can use [] to combine string to change the range.

>> for i=1:4
Range=['A' num2str(i)]
end
Range =
A1
Range =
A2
Range =
A3
Range =
A4

But,this is a bad way.You should open and write Excel file every time.



来源:https://stackoverflow.com/questions/8676763/how-to-export-data-from-matlab-to-excel-for-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!