I have 3 .m files and each one plots a graph. I need to superimpose the results from the three of them, so what I did is to copy the three codes into a single .m file.
The problem is that I need to clean (by using the command "clear"), between every program, and therefore, between every plot.
Anyone has any suggestion on how to plot the three results in a single figure, please?
Thanks! :-)
Try the following approach: a single file containing four functions.
function plotEverything()
[x1 y1] = data1();
[x2 y2] = data2();
[x3 y3] = data3(0.5);
figure
plot(x1, y1);
hold all;
plot(x2, y2);
plot(x3, y3);
title 'my awesome plot of everything';
xlabel 'X'; ylabel 'Y';
legend({'one', 'two', 'three'});
end
function [x y] = data1()
x = 1:5;
y = 0.5 * x;
end
function [x y] = data2()
x = 2:2:10;
y = sqrt(x);
end
function [x y] = data3(p)
x = linspace(0,7,15);
y = 0.1 * rand(size(x)) + p * x.^2;
end
Put it al in the file plotEverything.m
, and call it from the command line with plotEverything
. No need to explicitly clear any variables - anything that was created in any of the functions will be gone by the time the last function returns, and anything created by the individual functions (note I called everything x
, y
- that was deliberate) is invisible to the other functions as it has local scope.
Now the code is organized - there is a function just for plotting, and a function for generating the data that goes into each of the plots. Obviously your functions data1
etc will be more complicated than mine, but the idea is the same.