Search code examples
matlabmatlab-figure

Save multiple figures in one pdf


I am trying to save/combine all the existing figures, created in a loop, in one pdf file instead having multiple pdfs. Let's say one figure per page.

x = rand(5,100); 
y = rand(5,100); 

for i = 1:5 
    plot(x(i,:), y(i,:)); 
    filename_string = ['Plot_Number_', num2str(i),'_' ,'pdf']; 
    print(gcf, '-dpdf', '-r600', filename_string); 
    saveas(gcf,'testx', 'pdf');
end

Solution

    • Add figure on every plot, this will keep each plot on different window
    • Make the filename_string the plot title
    • Name the code with the plot, i.e filename.m

    • Make another m file, let's say main.m
    • Use publish(filename', options) to get the pdf file filename.pdf
    • Before using publish define the options
    options.format = 'pdf'
    options.showCode = false
    

    Run main.m and check the current directory you may see an HTML directory where you can find the pdf file named filename.pdf


    Code is as follows


    filename.m

    close all
    clear
    clc
    x = rand(5,100); 
    y = rand(5,100); 
    
    for i = 1:5 
        figure% keep plots on different windows
        plot(x(i,:), y(i,:)); 
        title(['Plot Number ', num2str(i)], 'color', 'red', 'fontSize', 25)
    end
    

    main.m

    close all
    clear
    clc
    options.format = 'pdf';
    options.showCode = false;
    publish('filename.m', options)