I have the following MATLAB code:
for i=1:3
a=rand(5,1);
b=rand(5,1);
plot(a,b);
xlabel('X Values');
ylabel('Y Values');
xlswritefig(gcf, 'Results.xlsx', 'Sheet1', 'D2')
% from https://www.mathworks.com/matlabcentral/fileexchange/24424-xlswritefig
end
This generates just the 3rd plot in an Excel file. However, I want to generate all 3 plots, side-by-side, in a single Excel file. How can I do this?
EDIT:
I modified the code to use actxserver
instead of xlswritefig
. However, as the code runs, it generates 3 excel pop-ups showing the plots. However, the file results1.xlsx
contains no plots. I don't even want peaks
in the code, but if I exclude it, nothing even shows up in the Excel pop-ups. Here's the new code:
cellPos = {'D2', 'J2', 'P2'};
for i=1:3
a=rand(5,1);
b=rand(5,1);
plot(a,b);
xlabel('X Values');
ylabel('Y Values');
f1 = figure; peaks;
% Connect to Excel, make it visible and add a worksheet
xl = actxserver('Excel.Application'); set(xl,'Visible',1);
xl.Workbooks.Add(1); xls = xl.ActiveSheet;
% Paste in the MATLAB figures
print(f1, '-dbitmap'); xls.Range(cellPos{i}).PasteSpecial;
xls.Shapes.Item(1).PictureFormat.CropLeft = 30;
xls.Shapes.Item(1).PictureFormat.CropRight = 30;
xls.Shapes.Item(1).Height = 100;
xls.Shapes.Item(1).Left = xls.Range(cellPos{i}).Left;
excel = actxserver('Excel.Application'); % Create server object
excelWorkbook = excel.Workbooks.Add(1); % Add a workbook
excelWorkbook.SaveAs('results1.xlsx'); % Save workbook to a file
excelWorkbook.Close(); % Close workbook
excel.Quit(); % Quit server
excel.delete(); % Delete server object
end