Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture2 Notes

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

Lecture 2 : Matlab Basics II

This lecture covers the following topics:

· The assignment operator “=” for defining variables


· Creating and manipulating arrays
· Element-by-element array operations: The “.” operator
· Vector generation with linspace function and “:” (colon) operator
· Graphing data and functions
The Assignment Operator “=” for Defining Variables

Matlab does not use the “=” sign for expression evaluation, say, 1+2 =. It returns
an error.

In Matlab the “=” sign is reserved for assigning a value (numeric or text) to a
variable:

Variables are cataloged in the Workspace Window:


Examples of the use of scalar variables

Note: The instruction clc clears the Command Window from all previously typed
commands and answers, but it does not clear the defined variables. Another useful
instruction is the home instruction that scrolls the Command Window and sends the
cursor to the upper left hand side of the window. Try it.
Rules on variable names:

1. Must begin with a letter.


2. Can be up to 63 characters.
3. Can contain letters, digits and the underscore ‘_’ character (e.g., Ab23_x).
4. The variable name is case sensitive (A123 is not the same as a123).
5. No spaces are allowed.
6. Avoid using built-in function names (cos, sin, abs, sqrt, etc.) and avoid using
Matlab predefined constant names (e.g., i, j, pi, ans, inf, Inf, eps, NaN, etc.)
7. Avoid using Matlab keywords such as: break, if, else, end, case, function, for,
while, switch, etc. (iskeyword returns the complete list).

Useful commands for managing variables

Command Outcome
clear Removes all variables from memory
clear x y z Removes only variables x, y and z from memory
who Displays a list of variables currently in memory
whos Displays a detailed list of variables currently in memory

Examples:
Creating and Manipulating Arrays

One of the main advantages of using Matlab for numeric calculations and
programming is its relative ease of creating and manipulating arrays (vectors and
matrices), and its efficient array computations (the name Matlab stands for Matrix
Laboratory).

A vector is a one-dimensional array. It could be represented by a row vector or a


column vector. A=[1 2 -5] is a 1x3 row vector (one row by three columns). This is
how it is created in Matlab:

The transpose of A is a column vector B of dimensions 3x1 (three rows by one


column). In array notation, B = AT, where T stands for the transpose operator.
Matlab uses the (apostrophe) symbol to perform the transpose operation:
The vector B can also be entered as:

One can selectively assign one element of an array to a new variable by using
an“index” that points to the element of interest. For example, to assign the third
element of vector A to a variable d, we use the instruction d=A(3)

A two-dimensional array (matrix) Example:


The and instructions for arrays

The instruction returns the dimensions of an array (vector or matrix) as a row


vector: [# of rows # of columns]. The length command returns a scalar that is
equal to the number of elements in a vector. For a matrix, length returns the largest
of the number of rows and the number of columns.

For a matrix:

For a (row or column) vector:


For a scalar, the size instruction always returns a 1x1 array. The length instruction
returns 1. In fact, Matlab treats all scalars as 1x1 arrays.

The empty (or null) array []:


Generation of special arrays ( and )
Element-by-Element Array Operations: The “.” Operator

Matlab has a powerful way for processing the individual components of a vector or
a matrix. For example, if x is a row (or column) vector, the expression 2*x
multiplies each individual component of x by 2. Similarly, 1+x and sqrt(x) are
designed to compute the element-by-element addition of 1 and the element-by-
element square root of vector x, respectively. This is true for all Matlab elementary
(and trig) built-in functions. Here is an example:

However, care must be used when trying to perform exponentiation (say, x^2) of
the components of x. Here, the “ ^” operator must be used:

Similarly, ‘.*’ must be used for element-by-element multiplication of two arrays:


In the above example, the arrays must have the same dimensions, otherwise an error
occurs:

Continuing with the x and y vectors defined in the above example, Matlab returns
the following for y*x (no dot) and x*y. Why?
So, the rule is that when performing (element-by-element multiplication (*),
division (/) or exponentiation (^) of a vector we must use the “ *”, “ /”, and “ ^”
operators. The dot notation is optional for multiplication and division by a scalar
(constant). Here are few more examples:

The dot is optional in the following example (let, x = [1 2 3]):


Some useful array commands
Here is a list of several useful commands that compute the sum, product, minimum
value, maximum value, mean value, variance and sort of a vector x: sum(x), prod(x),
min(x), max(x), mean(x), var(x), sort(x).

Examples:

Use the help utility to learn more about these Matlab commands and their available
options.
Vector Generation with Function and “ ” colon Operator

The linspace(x1, x2, n) function provides a handy tool to generate a row vector of n
equally spaced points between x1 and x2. If the integer n is omitted, the function
generates 100 points (by default). The increment between consecutive values is
given by

Similarly, the logspace(x1, x2, n) function generates a row vector of n


logarithmically, equally spaced points between 10 x1 and 10x2. If n is omitted, the
function generates 50 points.

Try: logspace(0, 5, 6) and logspace(0.2, 0.6, 3).

Can you find a formula for the intermediate values generated by the command
logspace(x1, x2, n)?
The Colon Operator “:”

The colon operator is a powerful tool for creating and manipulating arrays. The
Matlab expression x = 1:6 generates a row vector with values 1, 2, 3, ... 6. The
expression y = 1:0.5:3.2 generates a row vector with values 1, 1.5, 2, 2.5, 3. Here,
the 0.5 is the increment. Here are few more examples:

In the last example, the instruction format short g suppresses the redundant zeros on
the right of all displayed numerical results.
The colon operator can also be used as a wildcard to select the individual rows and
columns of a matrix (or vector). So, if x = [1 2 4 3 -1 10], then x(2:4)= x([2 3 4])
returns the row vector [2 4 3]. Here are two examples:

Your turn: Explain the result returned by the following Matlab instructions:
>>eye(3,4)

>>v=[1 2 3];
>>A=diag(v)

>>B=[ 1 2 3; 4 5 6; 7 8 9];
>> diag(B)

>>x=0:6;
>>x(1:3)=[]

>>A=[1 2 3 ; 2 -3 4; 0 2 -1];
>>A(:,1)=[];
>>A

>>x=[1 2 3 -1 0];
>>y=fliplr(x)
Application of “:” in summing series:
Find the sum of the first ten terms of the following geometric series, and compare it
to the exact value, 3/7.

0.3 3
= (0.3) = =
1 − 0.3 7

Matlab solution:

Note: S is computed as 0.3^1+0.3^2+ …. + 0.3^9+0.3^10 in the above example.

You might also like