You are on page 1of 49

Command Window

Edit Window
Function M-file
Script M-file
1.1.2 Script M-files and function M-files
Commands can be entered in command window, or stored
in a script M-file or a function M-file. Using the command
window for calculations is an easy and powerful tool.
However once you close the MATLAB program, all your
calculations are lost. To avoid loss of programs, the user
can create and save code in the so called M-files. Once
saved, these files can be reused by the programmer.
A script M-file can call a function M-file to perform certain
calculations and then return command to the script file.
Using Command window only:

>> x = 10;
>> area = pi*x^2
Using Command window and function M-
file
In the edit window create a function as follows:

function f = circle(x)
f = pi*x^2
End

Notation:
f is the output
circle is the function name
x is input argument (a scalar or vector).
The MATLAB input argument (x) is used to pass data between the function and command window or a script file or
another function.
The user must save the function in a folder with an identical name to the function name. Therefore save the
function under the name circle.m.
Then in the command window type:

>> x = 10;
>> circle(x)
Using a script file only:
Go to the edit window, create and save a script file with the
name test1.m

x = 10;
area = pi*x^2;

In the command window type:


>> test1
Using script file and function M-files
With the function circle.m already in the current folder, go to the
edit window and create a new script file:

x = 10;
circle(x)

Save file under the name run_circle.m.


In the command window enter this script file name (without the
extension .m):
>> run_circle
Manipulating MATLAB Matrices

Matrices are defined as follows:


>>A = [3.5]; The semicolon suppresses output to screen
>>B = [1.5,3.1]; Or B=[1.5 3.1];
B is a row vector
>>C = [1;2];
C is a column vector
>>D = [-1, 0, 0; 1, 1, 1; 0, 0, 2];
D is 3x3 matrix
>>S = [3.0, B]
MATLAB returns: S = 3.0 1.5 3.1
>>T = [1, 2, 3; S]
MATLAB returns: T = 1 2 3
3 1.5
3.1
>>H = 1:6
MATLAB returns: H = 1 2 3 4 5 6
>>Time = 0.0:0.5:2.0
MATLAB returns: 0 0.5 1.0 1.5 2.0
Let
>>M = [1 2 3 4 5;
2 3 4 5 6;
3 4 5 6 7]
We can extract column 1 from matrix M with
the command >>X = M(:,1) which returns X
= 1
2
3
We read the syntax (:,1) as “all the rows in
column 1”. Similarly, we can extract row 2 from
matrix M with the command >>y = M(2,:)
which returns Y = 2 3 4 5 6.
We read the syntax (2,:) as “all the columns in
row 2”

You might also like