1
votes

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! :-)

3
It is not ideal to have lots of variables at the top level (command line scope). If you wrap your scripts inside a function the variables are cleared automatically when the function returns (as they go out of scope). Worth thinking about. - Floris
Why not convert the scripts to functions that output the data to plot so you can gather it in one place? - excaza
@excaza - I was writing that in an answer as you posted your comment… :-) - Floris
yeah, that's a nice idea!! I will try that! The only issue is that I have lots of variables, but it sounds like the best option! thank you very much!! :-) - Natiya

3 Answers

3
votes

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.

2
votes

You can use this line:

clearvars -except YourVariables

In which YourVariables are the ones you want to keep.

1
votes

I believe as you clear you variables after each script , that means you do not need the variables from one script to run the other. So you can use this

figure; %// a figure will open up
hold on;
call script 1
clear;
call script 2
clear;
call script 3;
clear;

Noe the figure opened at the start will have all the superimposed plots.

Also take care that none of your scripts should call figure command(they can call plot command) or else a new figure will open up and plots will not be superimposed