logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

Tutorial Lesson: Matlab Code (Creating, Saving, and Executing a Script File)



You'll learn to create Script files (MATLAB code) and execute them.

A Script File is a user-created file with a sequence of MATLAB commands in it. You're actually creating MATLAB code, here. The file must be saved with a '.m' extension, thereby, making it an m-file.

The code is executed by typing its file name (without the '.m' extension') at the command prompt.

Now you'll write a script file to draw the unit circle of Tutorial Lesson 3.
You are essentially going to write the same commands in a file, save it, name it, and execute it within MATLAB.

Follow these directions:

Create a new file. On PCs, select 'New' -> 'M-File' from the File menu, or use the related icons.

 icons to create Matlab code

A new edit window appears.

Type the following lines into this window. Lines starting with a '%' sign are
interpreted as comments and are ignored by MATLAB, but are very useful for you, because then you can explain the meaning of the instructions.



% CIRCLE - A script file to draw a pretty circle

angle = linspace(0, 2*pi, 360);
x = cos(angle);
y = sin(angle);
plot(x,y)
axis('equal')
ylabel('y')
xlabel('x')
title('Pretty Circle')
grid on



Write and save the file under the name 'prettycircle.m'.

On PCs select 'Save As...' from the File menu. A dialog box appears. Type the name of the document as prettycircle.m. Make sure the file is being saved in the folder you want it to be in (the current working folder / directory of MATLAB).

Click on the 'Save' icon to save the file.

Now go back to the MATLAB command window and type the following command to execute the script file.

>>prettycircle
 
 matlab code
 
And you achieve the same 2D plot that you achieved in Tutorial Lesson 3, but the difference is that you saved all the instructions in a file that can be accessed and run by other m-files! It's like having a custom-made code!

You're doing great!


From 'Matlab Code' to home

From 'Matlab Code' to 'Matlab Tutorial'
 



footer for matlab code page