Introduction To MATLAB: Kathmandu University

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Introduction to MATLAB

Kathmandu University
Mathematics Group

1 M-files
MATLAB has two M-files. They are script files and function files.
Both are called M-files, because they have a file extension of .m.
Where to type? Select new M-file from the file menu. A new edit
window will appear. Type M-files in this window.
Scripts files:
A script file is a user-created file with a sequence of MATLAB command
in it. It is equivalent to typing all the commands stored in the script
file, one by one, at the MATLAB prompt in the command window.
The file must be saved with a .m extension to its name, thereby,
making it an M-file. The file name must begin with a letter and the
rest of the character may include digits and underscores but not period
other than the last one .m.
The script file can execute by typing its name (without the .m ex-
tension)in the command window.
Script files work on global variables, that is, variables currently
present in the workspace. Results obtained from executing script files
are left in the workspace.
Script files are useful when we have to repeat a set of commands several
times.
Script files may be used to enter a data into huge matrices, since entry
error can be easily corrected.

2 Helpful built-in-functions used in M-files


input function:

The input function displays a prompt string in the command window


and then waits for the user to type in a response. For example, consider the
following statements:

1
my_val = input(Enter the input value: );

If the input function includes the character s as a second argument, then the
input data is returned to the user as a character string. Thus, the statement

>> in1 = input(Enter data: );


Enter data: 1.34

stores the value 1.34 into in1, while the statement

>> in2 = input(Enter data: , s);


Enter data: 1.34

stores the character string 1.34 into in2.

disp function:

The disp function displays the data. The disp function accepts an array
argument, and displays the value of the array in the command window. If the
array is of type char, then character string contained in the array is printed
out.
This function is often combined with the functions num2str (converts
a number to string) and int2str (converts an integer to string) to create
message to be displayed in the command window. For example, the following
MATLAB statements

>> str = [The value of pi = num2str(pi)];


>> disp(str);

will display The value of pi = 3.1416 in the command window. The first
statement creates a string array containing the message, and the second
statement displays the message.

fprintf function:

An even more flexible way to display data is with the fprintf function.
The fprintf function displays one or more values together with related text
and lets the programmer control the way the displayed values appear. The
general form of this function when it is used to print to the command window
is

fprintf(format, data)

where format is a string describing the way the data is to be printed, and
data is one or more scalars or arrays to be printed. The format is a character
string containing text to be printed plus special characters describing the
format of the data. For example, the function

fprintf(The value of pi is %f \ n , pi)

2
will print out The value of pi is 3.141593 followed by a line feed. The
character %f is a conversion character. It indicates that the value in the data
list should be printed out in floating point format at that location in the
format string. The character \ n is an escape character. It indicates that
a line feed should be issued so that the following text starts on a new line.
Other characters are as shown in table below.

Format string Results


%d display value as an integer
%e display value in exponential format
%f display value in floating format
%g display value in either floating format or
exponential format, whichever is shorter
\n skip to new line

fprintf(The value of pi is %8.2f \ n , pi)

will print out The value of pi is 3.14 followed by a line feed. The
conversion %8.2f indicates that the first data item in the function should be
printed out in floating point format in a field eight characters wide, including
two digits after the decimal point.

Its limitation: It displays only the real portion of a complex value.

>> x = 2 + 3*i;
>> str = [disp: x = num2str(x)];
>> disp(str);
>> fprintf(fprintf: x = %8.4f \n , x);

The results printed out by these statements are

disp: x = 2+3i fprintf: x = 2.0000

Problem 1 Write a script file to draw a unit circle whose parametric equa-
tion is given by
x = cos(), y = sin (), 0 2
Solution steps:

Select New M-file from the file menu. A new edit window will appear.

Type the following lines into this edit window. Lines starting with %
sign are interpreted as comment line by MATLAB and are ignored.

% Script file: circle.m


%
% Purpose:
% This program plots the unit circle.

3
%
% File written to give idea to students how to creat a script file.
% Dated on Feb 4, 2008.
%
% Define Variables:
% theta --- angle in radian.
% x --- x = cos(theta).
% y --- y = sin(theta).
%--------------------------------------------------------------------------
% Create array for input variables
theta = linspace(0, 2*pi, 100); % creat vector data
x = cos(theta); % generates x - coordinates
y = sin(theta); % generates y - coordinates

% Creates plot
plot(x,y); % plot the unit circle
axis(equal); % set equal scale on axes
title(Circle of unit radius); % put a title
text(0.5,0.5,note this); % put text at specified point

Select save as from file menu. A diaglog box will appear. Type the name
of the document as circle.m in the folder you want to be. Then click
yes to save the file.
Now to get back to MATLAB type the following in the command win-
dow.

>> help circle


>> circle

This will display the graph for unit circle.


Function files:
If we want to do a big set of computations but in the end we want only
a few outputs, a script file is not the right choice. What we need in
this case is a function file.
A function file is also an M-file, like a script file, except it has a function
definition line on the top that defines the input and output explicitly.
The general form of MATLAB function is

function [outarg1, outarg2, ...] = fname(inarg1, inarg2, ...)

The followings are the forms of MATLAB function if there is single


output or no output.

function [output] = fname(inarg1, inarg2, ...) function output =


fname(inarg1, inarg2, ...) function [ ] = fname(inarg1, inarg2,
...) function = fname(inarg1, inarg2, ...)

4
The function file must be saved in your required folder with the file
name fname.m.

The function file can execute by giving the values of the input argu-
ments by typing the format of function file in the command window.

Function files work on local variables. That is results obtained from


executing function files are not left in the workspace.

Problem 2 Write a function file to draw a circle of a specified radius, with


the radius as the input to the function.
Solution steps:

Select New M-file from the file menu. A new edit window will appear.

Type the following lines into this edit window. Lines starting with %
sign are interpreted as comment line by MATLAB and are ignored.

function [x,y] = circlefn(r)


% CIRCLEFN --- Draws a circle of a specified radius r.
% -------------------------------------------------------------------------
%
% CALL SYNTAX: [x,y] = circlefn(r); or just circlefn(r);
% Input: r = specified radius
% Output: [x,y] = the x- and y- coordinates of data points
% Dated on Feb 10, 2008.
% --------------------------------------------------------------------------
theta = linspace(0,2*pi,100); % creat vector data
x = r*cos(theta); % generates x - coordinates
y = r*sin(theta); % generates y - coordinates
plot(x,y,LineWidth,3); % Plot the circle with 3 pixels
axis(equal); % set equal scale on axes
title([Circle of radius r = , num2str(r)]);% put the title with the
% value of r

Select save as from file menu. A diaglog box will appear. Type the name
of the document as circlefn.m in the folder you want to be. Then click
yes to save the file.

Now to get back to MATLAB type the following in the command win-
dow.

>> help circlefn


>> circlefn(3)

This will display the circle of radius 3 having pixels 3.

You might also like