variables in matlab
TRANSCRIPT
CIV1900: Engineering Skills
Variables in MATLAB
Variables allow you to store (intermediate) results
• a variable is a named location in computer memory• for storing/retrieving one or more values
• created in MATLAB by assignment
radius = 3• accessed by mentioning the name (or in Workspace)
>>radiusradius =
3• can be used anywhere a number (literal) can be used
area = pi*radius^2
CIV1900 Engineering Skills: programming in MATLAB 2
Variables in MATLAB
• variables are listed in alphabetical order in the Workspace• with information about their name, size, type and min/max• not all information is shown automatically• use View > Choose Columns when focus is in the Workspace
• MATLAB automatically creates a variable called ans if needed:
>> 1024^3/8ans=134217728• If you don't want to print out the result add a semi-colon
>> diameter = 2*radius;
3Engineering Skills: programming in MATLABCIV1900
Assignment might look like algebra, but it isn't
• x = x + 1 doesn't sound right• how can x be equal to x + 1• why isn't it a logical inconsistency?
• because assignment isn't equality at all
• assignment is a two step process:• calculate the value on the right hand side (r-value)• store the result in the variable on the left hand side (l-value)
• So x = x + 1 means:• evaluate x + 1 first by getting the value out of variable x• store the result back into variable x
4Engineering Skills: programming in MATLABCIV1900
MATLAB arrays are collections of (like) values
• arrays store multiple elements of one type• each element can be accessed by position in the array
• called indexing or subscripting the array• uses the array name and then the index in
parentheses• most other programming languages index from 0
5Engineering Skills: programming in MATLABCIV1900
1-dimensional arrays are called vectors
• created with square brackets and (optional) commas
pos = [1, 0, -1]primes = [1 2 3 5 7 11 13]
• accessed with indices e.g. the 6th prime number is?
primes(6)ans = 11
• notice how vectors appear in the Workspace (e.g. size 1x7)
6Engineering Skills: programming in MATLABCIV1900
Vectors can be created using n:s:m notation
• vectors ranging from n to m with step s can be written n:s:m e.g. from 1 to 20 stepping by 3:
x = 1:3:20x = 1 4 7 10 13 16 19
• if the step size is missing, the default is 1:
x = 1:7x = 1 2 3 4 5 6 7
• the vector goes up to and including the last value• think about what might happen with negative values!
7Engineering Skills: programming in MATLABCIV1900
MATLAB has functions to create vectors with fixed sizes
• linspace takes a n and m, and a number of elements:• e.g. create a vector from 0 to 3 containing 5 values
linspace(0, 3, 5)ans = 0 0.7500 1.5000 2.2500 3.0000
• zeros and ones create vectors of only zeros and ones
zeros(1, 5)ans = 0 0 0 0 0ones(1, 5)ans = 1 1 1 1 1
8Engineering Skills: programming in MATLABCIV1900
Indexing is used to make vectors longer or shorter
• assigning to an index beyond the length grows the vector
data = [1 2 3];data(6) = -1data = 1 2 3 0 0 -1
• zeros are used to fill in the gaps
• assigning an empty vector to an index removes elements
data(2) = []data =
1 3 0 0 -1
9Engineering Skills: programming in MATLABCIV1900
Boolean vectors can be used to select elements
• booleans are true/false (that is, yes/no values) of type logical
primes = [1 2 3 5 7 11 13];mask = [true false true false]mask = 1 0 1 0primes(mask)ans = 1 3
• the new vector is the length of the number of true values• booleans may look like numbers when printed
but they are a different type
10Engineering Skills: programming in MATLABCIV1900
Index vectors can select elements in any order
• each element in the index vector selects an element
primes = [1 2 3 5 7 11 13];indices = [1 6 4];primes(indices)ans = 1 11 5
• the index vector can be of any length• the new vector has the same length as the index vector• the index vector can be created using n:s:m range notation• the special value end can be used in these ranges
11Engineering Skills: programming in MATLABCIV1900
Arrays can store many dimensions
• matrices are two dimensional arrays• created with semi-colons to separate the rows:
x = [1 2 3; 4 5 6; 7 8 9]x = 1 2 3 4 5 6 7 8 9
• accessed using a pair of indices (row first, then column)
x(1, 3)ans = 3
• functions like zeros and ones work too
12Engineering Skills: programming in MATLABCIV1900
Functions apply to arrays in different ways
• some functions apply to all elements of an array
• e.g. min, max, sum, …values = [0 5 -2];sum(values)ans = 3
• others apply to each element one at a time
• e.g. trig functions, absolute value (abs), …abs(values)ans = 0 5 2
13Engineering Skills: programming in MATLABCIV1900
Special operators exist for per element calculations
• the regular operators sometimes behave differently on arrays• e.g. * does not multiply corresponding array elements
[1 2 3]*[4 5 6]gives the error: Inner matrix dimensions must agree
• because * is matrix multiply (more about this in later weeks)
• we need array multiply which multiplies each pair of elements
to create a new array:
[1 2 3].*[4 5 6]ans = 4 10 18
14Engineering Skills: programming in MATLABCIV1900
Concatenating and slicing matrices
15
>> a=[1 2 3; 5 7 9; 8 9 10]>> b=[9 8 7; 6 5 4; 1 2 3]
• What would be the result?
>> c=[a b]
c = 1 2 3 9 8 7 5 7 9 6 5 4 8 9 10 1 2 3
>> d=[a; b]d = 1 2 3 5 7 9 8 9 10 9 8 7 6 5 4 1 2 3
>> e=a(1,:) e = 1 2 3“1” means “the first row”
“:” means “all columns”
>> f=a(:,1)f = 1 5 8“:” means “all rows”
“1” means “the first column”
Engineering Skills: programming in MATLABCIV1900
Deleting rows and columns
16
• Easy, by using []>>cc = 1 2 3 9 8 7 5 7 9 6 5 4 8 9 10 1 2 3
• To delete the second column:>> c(:,2)=[]c = 1 3 9 8 7 5 9 6 5 4 8 10 1 2 3
• To further delete the second row:>> c(2,:)=[] c = 1 3 9 8 7 8 10 1 2 3
Engineering Skills: programming in MATLABCIV1900
17
Transpose of a matrix
17
• If a is a m x n matrix, then the transpose of a, denoted with a’, is a n x m matrix whose first column is the first row of a, whose second column is the second row of a, and so on
• In Matlab we can compute the transpose of a matrix using the dot-apostrophe operator ‘
>>a=[1 2 3 4; 5 7 9 3; 8 9 10 12]a = 1 2 3 4 5 7 9 3 8 9 10 12>> a'ans = 1 5 8 2 7 9 3 9 10 4 3 12
3 x 4
4 x 3
Engineering Skills: programming in MATLABCIV1900
18
Generating basic matrices
18
• zeros() – all elements are 0>> zeros(2,3)ans = 0 0 0 0 0 0
• ones() – all elements are 1>> ones(2,3)ans = 1 1 1 1 1 1
• rand() – uniformly distributed random elements from (0,1)
>> rand(2,3)ans = 0.8147 0.1270 0.6324 0.9058 0.9134 0.0975
• eye() – identity matrix>> eye(3)>>ans = 1 0 0 0 1 0 0 0 1
>> eye(5)ans = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
CIV1900 Engineering Skills: programming in MATLAB
19
• Done element by element• Matrices must have the same dimensions>> a=[1,2,3; 5,7,9; 8,9,10]a = 1 2 3 5 7 9 8 9 10>> b=[9,8,7; 6,5,4; 1,2,3]b = 9 8 7 6 5 4 1 2 3
• What would be the result?>> c=a+bc = 10 10 10 11 12 13 9 11 13
Adding and subtracting matrices
>> d=a-bd = -8 -6 -4 -1 2 5 7 7 7
Engineering Skills: programming in MATLABCIV1900
20
• Each matrix element is multiplied by the scalar
>> a=[1,2,3; 5,7,9; 8,9,10]a = 1 2 3 5 7 9 8 9 10
>> b=a*6b = 6 12 18 30 42 54 48 54 60
• Do we need to use .* instead of * ?
Multiplying a matrix with a scalar
Engineering Skills: programming in MATLABCIV1900
Calculating the inverse matrix
• Let a, b and c are square matrices, a*b=c and we are given a and c and need to find b
>> a=[9 2 7; 6 1 4; 1 6 3]>> c=[1 2 3; 5 7 9; 8 9 10]
• Let’s do it analytically:
21
• In Matlab we can use inv():
>> b=inv(a)*cb = 5.9643 7.8214 9.6786 4.7857 5.9286 7.0714 -8.8929 -11.4643 -14.0357
cabcaaba
cab
1
1
1
multiply both sides on theleft by 1a
, where I is the identity matrixIaa 1
Engineering Skills: programming in MATLABCIV1900
Matlab can manipulate not only numbers but also strings
• A character string or simply string is an ordered sequence of characters (i.e. symbols and digits)
• In Matlab strings are enclosed in single quotes
>> s1 = 'Hello!'
s1 = Hello!
>> s2 = 'I am 20 years old.'s2 = I am 20 years old.
• Single quotes can be included in the strings with double quotes>> s4 = 'You''re smart's4 = You're smart
22Engineering Skills: programming in MATLABCIV1900
Matlab treats strings as arrays of characters
• We can apply the vector manipulation functions• What is the result?>> s1 = 'James';>> size(s1)ans = 1 5
>> length(s1)ans = 5
>> s1(3)ans = m
>> s1(6)??? Attempted to access s1(6); index out of bounds
because numel(s1)=5.
23Engineering Skills: programming in MATLABCIV1900
Displaying string variables with disp()
• We already have seen how to use disp() • num2str() must be used to convert numbers intro strings,
which are then concatenated with other strings in disp()
>> disp(6)6
>> disp(['My favourite number is ', a])My favourite number is
>> disp(['My favourite number is ', int2str(a)])My favourite number is 6
24Engineering Skills: programming in MATLABCIV1900
Displaying string variables with fprintf()
• There are other display and print functions which do not require numbers to be converted to strings to display information, e.g. fprintf()
>> fprintf('My favourite number is %d \n', a);My favourite number is 6
%d – print the value of the variable a as an integer
\n – the cursor goes to a new line
Other useful formatting symbols:
%f – float point number
%s – string
\t – insert tab
2525Engineering Skills: programming in MATLABCIV1900