- You should learn to write functions instead of scripts;
- Use hold on
HOW TO PLOT ON THE SAME FIGURE PLOTS OF DIFFERENT SCRIPTS
6 次查看(过去 30 天)
显示 更早的评论
Hi, I'm in truble because I have two programs with the same variables and parameters. The main of the study is to change a value and plot the results. The problem is that I want them on the same plot but I use the same name for the variabes in the two different programs so when I use some function to join the figures togheter matlab resets the values obtained in the first program and runs only the second one.
Is there a method to avoid changing all the names of the variables in one of the two programs (because they have something like 500 lines)?
4 个评论
Walter Roberson
2023-11-14
Run the first script. Then
set(findobj(groot, 'axes'), 'NextPlot', 'add');
Now run the second script.
回答(1 个)
Abhas
2024-8-8
Hi Pasquale,
You can plot two graphs with same variables and parameters in the same figure by using functions to encapsulate the code in each program which will ensure that the variables will be local to each function and won't interfere with each other. You can refer to the below example steps for better understanding:
- Let's create a file named "program1.m" with the variables 'x' and 'y'.
% Your code for the first program
x = linspace(0, 10, 100);
y = sin(x);
% Save the variables to a .mat file
save('program1_data.mat', 'x', 'y');
- Let's create another file named "program2.m" with the same variables 'x' and 'y'
% Your code for the second program
x = linspace(0, 10, 100);
y = cos(x);
% Save the variables to a .mat file
save('program2_data.mat', 'x', 'y');
- In the main script call the two files and record the variables. Now plot the graphs in the same figure.
% Clear workspace and close all figures
clear;
close all;
% Run the first program and save its data
run('program1.m');
% Load the data from the first program
data1 = load('program1_data.mat');
% Run the second program and save its data
run('program2.m');
% Load the data from the second program
data2 = load('program2_data.mat');
% Plot the results on the same figure
figure;
plot(data1.x, data1.y, 'r-', 'DisplayName', 'Program 1');
hold on;
plot(data2.x, data2.y, 'b--', 'DisplayName', 'Program 2');
hold off;
% Add labels and legend
xlabel('X-axis');
ylabel('Y-axis');
legend show;
title('Comparison of Program 1 and Program 2');
Output:
You may refer to the following MathWorks documentation links to have a better understanding on combining multiple plots:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Specifying Target for Graphics Output 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!