Hello,
To address the performance issues you're encountering, let's first identify which part of your code is consuming the most time. I recommend using the MATLAB Profiler app for this task.
As you can see from the profiler summary, the ‘getSnapshotImage’ function is the primary bottleneck. Additionally, creating a new figure for each iteration is another source of overhead.
Below, I've outlined some modifications to optimize your code:
import mlreportgen.report.*
rpt = Report('myreport', 'pdf');
fig = figure('visible', 'off');
plot_images = cell(1, num_plots);
filenames = cell(1, num_plots);
title(sprintf('Plot %d', i));
filenames{i} = sprintf('plot_%d.png', i);
print(fig, filenames{i}, '-dpng');
img = Image(filenames{i});
if exist(filenames{i}, 'file')
For 10 iterations, including the creation of sample data, the optimized code executes in ~2.7 seconds, compared to approximately 6 seconds for the original code.
The modifications I implemented is as follows:
- I have used ‘print’ function instead of ‘getSnapshotImage’ to save each plot directly as a PNG file, which is more efficient.
- A single figure object is reused across all iterations, reducing overhead.
Refer to the following MathWorks documentation for the more information:
- print - https://mathworks.com/help/matlab/ref/print.html
- Image - https://mathworks.com/help/rptgen/ug/image.html
- Profiler App - https://mathworks.com/help/matlab/ref/profiler-app.html
Hope this helps!