Matlab_06

Scripts

We are now going to move away from the command window and start a text file containing the instructions we want Matlab to execute. These files are called 'scripts'. You can use the menus:

File -> New -> Script

or

File -> New -> M-file

depending on which version of Matlab you are running.

Scripts work exactly the same as the command line but the commands in a script are executed only when you press the F5 key or click the Save and Run icon (green triangle) on the tool bar. Copy and paste this example in to your script then Save and Run it - you will be prompted for a file name the first time you do this.

x = [-5:0.1:5];
y_1 = x.*x;        % this gives us x squared
y_2 = x.*x.*x;     % this gives us x cubed
plot(x,y_1,'r');   % plot the x squared graph
hold on;           % hold the plot for a second line
plot(x,y_2,'g');   % plot x cubed

Now we can add a few bells and whistles. I introduce these new things without explanation because they are fairly obvious:

% preamble starts here
close all; % close all open figures
clear;     % clear all variables
clc;       % clear the command window
%
% graph drawing script starts here
x = [-5:0.1:5];
y_1 = x.*x;        % this gives us x squared
y_2 = x.*x.*x;     % this gives us x cubed
plot(x,y_1,'r');   % plot the x squared graph
hold on;           % hold the plot for a second line
plot(x,y_2,'g');   % plot x cubed
%
% some new things added to the graph
xlabel('x values');
ylabel('y values');
title('my first graph')
legend({'x^2' 'x^3'});
grid on;