[How To] Run a script to plot subplots in Octave


To demonstrate and perform POC's for some of the things that I learnt, I wrote a snippet of Octave script. The following is a very simple script to understand how to execute Octave script files and plot subplots.

Following are some of the things to keep in mind:
1. Octave scripts have a extension of  ".m". ie. a script/function file named myScript has to be saved with "myScript.r"
2. We need to change the directrory to the path at which the script resides. We can use pwd,cd to perform this navigation.
3. In order to add any directory containing the script in Ocatve search path, we can perform the below operation.. After doing so, we can execute all the script files in the folder from any other folder.
eg:addpath(genpath("C:\Users\sesa398967\Documents\MyLearnings"));

The plot function in Octave is used to plot graphs on XY axis in Octave. Similarly subplotis an extention to plot function to plot further smaller graphs inside the same window.

Below is the octave snippet:

  #declare a vector of 100 elements
  a=[1:0.5:50];

  #get a graph of 3*2 subplots and plot sin(a) function
  subplot(3,2,1);

  plot(sin(a));
  title("Sin function for a");
  legend("sin a");

  #plot cos(a) function
  subplot(3,2,2);
  plot(cos(a));
  title("Cos function for a");
  legend("cos a");

  #plot tan(a) function
  subplot(3,2,3);
  plot(tan(a));
  title("Tan function for a");
  legend("tan a");

  #plot cot(a) function
  subplot(3,2,4);
  plot(cot(a));
  title("Cot function for a");
  legend("cot a");

  #plot sec(a) function
  subplot(3,2,5);
  plot(sec(a));
  title("Sec function for a");
  legend("sec a");

  #plot cot(a) function
  subplot(3,2,6);
  plot(csc(a));
  title("Cosec function for a");
  legend("cosec a");

  #bye


How to run this script:
1. Save the above script to a text file with extension .m
eg.mysubplot.r
2. In the Ocatave terminal navigate to the directory in which the file resides.
3. Execute the script as by calling its name from the terminal.
eg: >> mysubplot

Output of the subplot script:
subplot function in Ocatve - www.ivishal.me
[click on the image to enlarge]