matlab homework
10/8/2014
1
MATLAB Introduction
What is MATLAB • High-level language and interactive environment for numerical
computation, visualization, programming and application
development
• Interactive environment for iterative exploration, design, and
problem solving
• Mathematical functions for linear algebra, statistics, Fourier
analysis, filtering, optimization, numerical integration, and solving
ordinary differential equations
• Built-in graphics for visualizing data and tools for creating custom
plots
• Development tools for improving code quality and maintainability
and maximizing performance
• Tools for building applications with custom graphical interfaces
• Functions for integrating MATLAB based algorithms with external
applications and languages such as C, Java, .NET, and Microsoft®
Excel®
10/8/2014
2
Desktop Basics
Current Folder —
Access your files.
Command Window — Enter commands
at the command line, indicated by the
prompt (>>).
Command History
— View or rerun
commands that
you entered at the
command line.
Workspace —
Explore data
that you
create or
import from
files.
Desktop Basics • As you work in MATLAB, you issue commands that create
variables and call functions.
• For example, create a variable named a by typing this
statement at the command line: a=1
>> a=1
a =
1
>> b=2
b =
2
>> c=a+b
c =
3
>> d = cos(a)
d =
0.5403
MATLAB adds variable a to the workspace and
displays the result in the Command Window.
10/8/2014
3
Desktop Basics • When you do not specify an output variable, MATLAB uses the
variable ans, short for answer, to store the results of your
calculation.
• If you end a statement with a semicolon, MATLAB performs
the computation, but suppresses the display of output in the
Command Window.
• You can recall previous commands by pressing the up- and
down-arrow keys, ↑ and ↓. Press the arrow keys either at an
empty command line or after you type the first few characters
of a command. For example, to recall the command b = 2,
type b, and then press the up-arrow key.
>> sin (a)
ans =
0.8415
>> e=a + b;
Desktop Basics
10/8/2014
4
Matrices and Arrays • MATLAB is an abbreviation for "matrix laboratory."
While other programming languages mostly work with numbers one at a time
• MATLAB is designed to operate primarily on whole matrices and arrays.
• All MATLAB variables are multidimensional arrays, no matter what type of data.
• A matrix is a two-dimensional array often used for linear algebra.
Array Creation
• To create an array with four elements in a single row,
separate the elements with either a comma (,) or a
space.
• This type of array is a row vector.
• To create a matrix that has multiple rows, separate
the rows with semicolons.
>> a = [1 2 3 4]
a =
1 2 3 4
>> a = [1 2 3; 4 5 6; 7 8 10]
a =
1 2 3
4 5 6
7 8 10
10/8/2014
5
Array Creation
• Another way to create a matrix is to use a function,
such as ones, zeros, or rand.
• For example, create a 5-by-1 column vector of zeros,
ones, and rand.
>> z = ones(5,1)
z =
1
1
1
1
1
>> z = rand(5,1)
z =
0.8147
0.9058
0.1270
0.9134
0.6324
>>z = zeros(5,1)
z =
0
0
0
0
0
Matrix and Array Operations
• MATLAB allows you to process all of the values
in a matrix using a single arithmetic operator
or function.
• To transpose a matrix, use a single quote ('):
>> a + 10
ans =
11 12 13
14 15 16
17 18 20
>> sin(a)
ans =
0.8415 0.9093 0.1411
-0.7568 -0.9589 -0.2794
0.6570 0.9894 -0.5440
>> a'
ans =
1 4 7
2 5 8
3 6 10
10/8/2014
6
Matrix and Array Operations • You can perform standard matrix multiplication, which
computes the inner products between rows and
columns, using the * operator. For example, confirm
that a matrix times its inverse returns the identity
matrix:
• Notice that p is not a matrix of integer values.
MATLAB stores numbers as floating-point values, and
arithmetic operations are sensitive to small
differences between the actual value and its floating-
point representation.
>> p = a*inv(a)
p =
1.0000 0 -0.0000
0 1.0000 0
0 0 1.0000
Concatenation
• Concatenation is the process of joining arrays
to make larger ones. In fact, you made your
first array by concatenating its individual
elements. The pair of square brackets [] is the
concatenation operator.
>> A = [a,a]
A =
1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
10/8/2014
7
Concatenation • Concatenating arrays next to one another
using commas is called horizontal
concatenation. Each array must have the same
number of rows. Similarly, when the arrays
have the same number of columns, you can
concatenate vertically using semicolons.
>> A = [a; a]
A =
1 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 10
Complex Numbers
• Complex numbers have both real and
imaginary parts, where the imaginary unit is
the square root of –1.
• To represent the imaginary part of complex
numbers, use either i or j.
>> sqrt(-1)
ans =
0 + 1.0000i
>> c = [3+4i, 4+3j, -i, 10j]
c =
3.0000 + 4.0000i 4.0000 + 3.0000i 0 - 1.0000i 0 +10.0000i
10/8/2014
8
Array Indexing • Every variable in MATLAB is an array that can hold
many numbers. When you want to access selected elements of an array, use indexing.
• For example, consider the 4-by-4 magic square A:
• There are two ways to refer to a particular element in an array.
• The most common way is to specify row and column subscripts, such as
>> A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> A(4,2)
ans =
14
Array Indexing • Less common, but sometimes useful, is to use a single
subscript that traverses down each column in order:
• Using a single subscript to refer to a particular element in an array is called linear indexing.
• If you try to refer to elements outside an array on the right side of an assignment statement, MATLAB throws an error.
.
>> A(8)
ans =
14
>> test = A(4,5)
Attempted to access A(4,5); index out of bounds because size(A)=[4,4].
10/8/2014
9
Array Indexing • However, on the left side of an assignment statement, you can specify
elements outside the current dimensions. The size of the array increases to accommodate the newcomers.
• To refer to multiple elements of an array, use the colon operator, which allows you to specify a range of the form start:end. For example, list the elements in the first three rows and the second column of A:
The colon alone, without start or end values, specifies allof the elements in that dimension. For example, select all the columnsin the third row of A:
>> A(4,5) = 17
A =
16 2 3 13 0
5 11 10 8 0
9 7 6 12 0
4 14 15 1 17
>> A(1:3,2)
ans =
2
11
7
>> A(3,:)
ans =
9 7 6 12 0
Array Indexing
• The colon operator also allows you to create
an equally spaced vector of values using the
more general form start:step:end.
• If you omit the middle step, as in start:end,
MATLAB uses the default step value of 1.
>> B = 0:10:100
B =
0 10 20 30 40 50 60 70 80 90 100
>> C = 0:10
C =
0 1 2 3 4 5 6 7 8 9 10
10/8/2014
10
Workspace Variables • The workspace contains variables that you create within or
import into MATLAB from data files or other programs. For example, these statements create variables A and B in the workspace.
• You can view the contents of the workspace using whos.
.
>> A = magic(4);
B = rand(3,5,2);
>> whos
Name Size Bytes Class Attributes
A 4x4 128 double
B 3x5x2 240 double
Workspace Variables • The variables also appear in the Workspace pane on the desktop.
• Workspace variables do not persist after you exit MATLAB. Save your data for later use with the save command,
• Saving preserves the workspace in your current working folder in a compressed file with a .mat extension, called a MAT-file.
• To clear all the variables from the workspace, use the clear command.
• Restore data from a MAT-file into the workspace using load.
>> save myfile.mat
>> load myfile.mat
10/8/2014
11
Character Strings
• A character string is a sequence of any number of characters enclosed in single quotes. You can assign a string to a variable.
• If the text includes a single quote, use two single quotes within the definition.
• myText and otherText are arrays, like all MATLAB variables. Their class or data type is char, which is short for character.
>>myText = 'Hello, world';
>> otherText = 'You''re right'
otherText =
You're right
Character Strings
• You can concatenate strings with square
brackets, just as you concatenate numeric
arrays.
• To convert numeric values to strings, use
functions, such as num2str or int2str.
>> longText = [myText,' - ',otherText]
longText =
Hello, world - You're right
>> f = 71;
>> c = (f-32)/1.8;
>> tempText = ['Temperature is ',num2str(c),'C']
tempText =
Temperature is 21.6667C
10/8/2014
12
Calling Functions
• MATLAB provides a large number of functions that perform computational tasks. Functions are equivalent to subroutines or methods in other programming languages.
• Suppose that your workspace includes variables A and B, such as
• To call a function, enclose its input arguments in parentheses:
>> A = [1 3 5];
>> B = [10 6 4];
>>max(A);
Calling Functions
• If there are multiple input arguments, separate them with commas:
• Return output from a function by assigning it to a variable:
• When there are multiple output arguments, enclose them in square brackets:
• Enclose any character string inputs in single quotes:
• To call a function that does not require any inputs and does not return any outputs, type only the function name:
• The clc function clears the Command Window.
>> max(A,B);
>> maxA = max(A);
>> [maxA,location] = max(A);
>> disp('hello world');
hello world
>> clc
10/8/2014
13
Line Plots • To create two-dimensional line plots, use the plot
function. For example, plot the value of the sine
function from 0 to 2π:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
0 1 2 3 4 5 6 7 -1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Line Plots
• You can label the axes and add a title.
0 1 2 3 4 5 6 7 -1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
x
s in
(x )
Plot of the Sine Function
>> xlabel('x')
>>ylabel('sin(x)')
>>title('Plot of the Sine Function')
10/8/2014
14
Homework
1. Use Matlab to plot the graph
� = 3�� + 5� − 12� − 9 for x ranging from 0 to 15.
2. If
A = 2 3 8
0 2 9
−1 15 7
and B = 5 6 8
4 2 1
3 −3 10 Find A+B, A-B, A+12, A*B and A*inv(B)