• Entering Matrices
• The best way for you to get started with MATLAB is to
learn how to handle matrices. Start MATLAB and follow along with each example.
• You can enter matrices into MATLAB in several different
ways:
• Enter an explicit list of elements.
• Load matrices from external data files.
• Generate matrices using built-in functions.
How to create a matrix in MATLAB
• Separate the elements of a row with blanks or
commas.
• Use a semicolon, ; , to indicate the end of each
row.
• Surround the entire list of elements with
square brackets, [ ].
• Examples:
• The Colon Operator
• The colon, :, is one of the most important MATLAB operators.
It occurs in several different forms. The expression 1:10
• is a row vector containing the integers from 1 to 10:
• 1 2 3 4 5 6 7 8 9 10
• To obtain nonunit spacing, specify an increment. For example,
• 100:-7:50
• Is 100 93 86 79 72 65 58 51
• and
MATLAB Matrices
• MATLAB treats all variables as matrices. For our
purposes a matrix can be thought of as an array, in fact, that is how it is stored.
• Vectors are special forms of matrices and contain
only one row OR one column.
• Scalars are matrices with only one row AND one
• A scalar can be created in MATLAB as follows:
• >> x = 23;
• A matrix with only one row is called a row vector. A row vector can be created in
MATLAB as follows (note the commas):
• >> y = [12,10,-3] • y =
• 12 10 -3
• A matrix with only one column is called a column vector. A column vector can be
created in MATLAB as follows:
• >> z = [12;10;-3] • z =
• 12
Generating matrices
• MATLAB treats row vector and column vector very differently • A matrix can be created in MATLAB as follows (note the
commas and semicolons)
• >> X = [1,2,3;4,5,6;7,8,9] • X =
• 1 2 3 • 4 5 6 • 7 8 9
• Matrices must be rectangular!
Extracting a sub-matrix
• A portion of a matrix can be extracted and
stored in a smaller matrix by specifying the names of both matrices and the rows and columns to extract. The syntax is:
• sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and
• Example :
• >> X = [1,2,3;4,5,6;7,8,9]
• X =
• 1 2 3
• 4 5 6
• 7 8 9
• >> X22 = X(1:2 , 2:3) • X22 =
• 2 3 • 5 6
• >> X13 = X(3,1:3)
• X13 =
• 7 8 9
• >> X21 = X(1:2,1) • X21 =
Matrix manipulation functions
• zeros : creates an array of all zeros, Ex: x = zeros(3,2)
• ones : creates an array of all ones, Ex: x = ones(2) • eye : creates an identity matrix, Ex: x = eye(3)
• rand : generates uniformly distributed random numbers in [0,1]
• diag : Diagonal matrices and diagonal of a matrix • size : returns array dimensions
• length : returns length of a vector (row or column) • det : Matrix determinant
• inv : matrix inverse
• eig : evaluates eigenvalues and eigenvectors • rank : rank of a matrix
Arrays
• Arithmetic operations on arrays are done
List of array operators
• The list of operators includes
• + Addition
• - Subtraction
• .* Element-by-element multiplication
• ./ Element-by-element division
• .\ Element-by-element left division
• .^ Element-by-element power
Using arrays to build tables
• Array operations are useful for building tables. Let us assume n is the column vector • n = (0:9)';
• Then
• pows = [n n.^2 2.^n]
• builds a table of squares and powers of 2: • pows =
M-files
• Learning objectives:
• Learning how to create well-documented M-files in the edit window and invoke them from the command window.
• We have now used the MATLAB® product
interactively in the Command Window. That is sufficient when all that is needed is a simple calculation.
• However, in many cases, many steps are
required before the final result can be
• An M-file consists of a series of statements
that can be run all at once. Note that the nomenclature “M-file” comes from the fact that such files are stored with a .m extension. M-files come in two flavors: script files and
Script files
• A script file is merely a series of MATLAB
commands that are saved on a file. They are useful for retaining a series of commands that you want to execute on more than one
occasion.
• The script can be executed by typing the file
name in the command window or by invoking the menu selections in the edit window:
• To create a script, click File, then New, then M-file. A new
window will appear called the Editor. To create a new script, simply type the sequence of statements (notice that line
numbers will appear on the left).
• When finished, save the file using File and then Save. Make
sure that the extension .m is on the filename (this should be the default). The rules for filenames are the same as for
variables (they must start with a letter, after that there can
• be letters, digits, or the underscore, etc.). By default, scripts
• area_circle.m
• % This program calculates the area of a circle • % First the radius is assigned
• radius = 5
Comments
• The first comment at the beginning of the
script describes what the script does.
Comments don’t affect what a script does, so the output from this script would be the same as for the previous version. The help
• The first block of comments (defined as contiguous lines at
the beginning)
• will be displayed. For example, for area_circle:
• >> help area_circle
• This program calculates the area of a circle
• The reason that a blank line was inserted in the script
Editing a script file
• Once the script has been executed, you may find
that you want to make changes to it (especially if there are errors!). To edit an existing file, there are several methods to open it. The easiest are:
• Click File, then Open, then click the name of the
file.
• Click the Current Directory tab (if it is not already
• sinncos.m
• % This script plots sin(x) and cos(x) in the same Figure • % Window for values of x ranging from 0 to 2*pi
• clf
• x = 0: 2*pi/40: 2*pi; • y = sin(x);
• plot(x,y,‘ro’) • hold on • y = cos(x); • plot(x,y,‘b+’)
• legend(‘sin’, ‘cos’)
2D Plotting
• >> x = linspace(0,2*pi,1000); • >> y = sin(x);
• >> z = cos(x); • >> hold on; • >> plot(x,y,‘b’); • >> plot(x,z,‘g’);
• >> xlabel ‘X values’; • >> ylabel ‘Y values’; • >> title ‘Sample Plot’;
• Method 2:
• >> x = 0:0.01:2*pi; • >> y = sin(x);
• >> z = cos(x); • >> figure
• >> plot (x,y,x,z);
• >> xlabel ‘X values’; • >> ylabel ‘Y values’; • >> title ‘Sample Plot’;
Setting Axis Limits
• By default, MATLAB finds the maxima and minima of the
data and chooses the axis limits to span this range. The axis command enables you to specify your own limits:
• axis([xmin xmax ymin ymax]) or for three-dimensional
graphs,
• axis([xmin xmax ymin ymax zmin zmax]) • Use the command
• axis auto
Create a script file for the data below
• Multiple data sets in one plot
• Multiple (x; y) pairs arguments create multiple graphs with a single call to plot. For
example, these statements plot three related functions of x: y1 = 2 cos(x), y2 = cos(x), and y3 = 0.5 cos(x), in the interval 0 ≤ x ≤ 2π.
• >> x = 0:pi/100:2*pi;
• >> y1 = 2*cos(x); • >> y2 = cos(x); • >> y3 = 0.5*cos(x);
• >> plot(x,y1,'--',x,y2,'-',x,y3,':') • >> xlabel('0 \leq x \leq 2\pi') • >> ylabel('Cosine functions')
• >> legend('2*cos(x)','cos(x)','0.5*cos(x)')
• >> title('Typical example of multiple plots')
Using the subplot function
• It can sometimes be useful to display multiple
plots on the same figure for comparison. This can be done using the subplot function, that takes arguments for number of rows of plots,
• clear all
• close all
• % subplot (nrows, ncols, plot_number)
• x=0:.1:2*pi; % x vector from 0 to 2*pi, dx = 0.1
• subplot(2,2,1); % plot sine function • plot(x, sin(x));
• subplot(2,2,2); % plot cosine function • plot(x, cos(x));
• subplot(2,2,3) % plot negative exponential function
• plot(x, exp(-x));
• subplot(2,2,4); % plot x^3
Scripts with input and output
• Let us create a script file called area_circle.m
and use input and output functions to
• area_circle.m
• % This script calculates the area of a circle
• % It prompts the user for the radius
• % Prompt the user for the radius and calculate
• % the area based on that radius
• radius = input(‘Please enter the radius: ’);
• area = pi * (radius^2);
• % Print all variables in a sentence format
• fprintf(‘For a circle with a radius of %.2f,’,radius)
• fprintf(‘the area is %.2f\n’,area)
• Executing the script produces the following output:
• >> area_circle
• Please enter the radius: 3.9
Example
• Write a script to calculate the area of a
Function files
• Function files are M-files that start with the
word function. In contrast to script files, they can accept input arguments and return
• The syntax for the function file can be
represented generally as
• function outvar = funcname(arglist)
• % helpcomments • statements
• where outvar = the name of the output
variable, funcname = the function’s name,
arglist = the function’s argument list (i.e.,
comma-delimited values that are passed into
the function), helpcomments = text that
provides the user with information regarding the function.
• The M-file should be saved as funcname.m so
disp and fprintf
• Output Statements: disp and fprintf
• Output statements display strings and the results of expressions, and can allow for formatting, or customizing how they are displayed. The simplest output
function in MATLAB is disp, which is used to display the result of an expression or a string without assigning any value to the default variable ans. However, disp
does not allow formatting. For example,
• >> disp(‘Hello’)
• Hello
• >> disp(4^3)
• 64
• Formatted output can be printed to the screen using the fprintf function. For example,
• >> fprintf(‘The value is %d, for sure!\n’,4^3)
• To the fprintf function, first a string (called the
format string) is passed, which contains any text to
be printed as well as formatting information for the expressions to be printed. In this example, the %d is an example of format information.
• The %d is sometimes called a placeholder; it
A list of placeholders in MATLAB
• %d integers (it actually stands for decimal
integer)
• %f floats
Input and output arguments
• The general form looks like:
• function [outputs] = function_name(inputs)
• Examples:
• function C=FtoC(F) One input argument and one
output argument
• function area=TrapArea(a,b,h) Three inputs and
one output
• function [h,d]=motion(v,angle) Two inputs and two
Example
• The function m-file below is according to
convention named fun.m
• function y=fun(t)
• % my function
• 1. Consider a triangle with sides a, b, and c and corresponding angles ab, ac, and bc.
• (a) Use the law of cosines, i.e., • c2 = a2 + b2 - 2ab cos ab;
• to calculate c if a = 3.7, b = 5.7, and ab = 79⁰. • (b) Then show c to its full accuracy.
• (c) Use the law of sines, i.e., •
• = , •
Exercises
• Write a function file that converts temperature in degrees
Fahrenheit (⁰F) to degrees Centigrade (⁰C). Use input and fprintf commands to display a mix of text and numbers. Recall the
conversion formulation, C = 5/9 * (F - 32).
• 3. Write a user-defined MATLAB function, with two input and two output arguments that determines the height in centimeters (cm) and mass in kilograms (kg)of a person from his height in inches (in.) and weight in pounds (lb).
• (a) Determine in SI units the height and mass of a 5 ft.15 in. person who weighs 180 lb.