Matlab
French
Introduction
French
logiciel = software
les boucles = loops
Taylor series is a representation of a function as an infinite sum of terms that are calculated from the values of the function's derivatives at a single point
Strain rate tensor
In continuum mechanics, the strain rate tensor is a physical quantity that describes the rate of change of the deformation of a material in the neighborhood of a certain point, at a certain moment of time. It can be defined as the derivative of the strain tensor with respect to time, or as the symmetric component of the gradient (derivative with respect to position) of the flow velocity.
Taylor series
A two-dimensional flow that, at the highlighted point, has only a strain rate component, with no mean velocity or rotational component.
Introduction
Intro to matlab (ml) commands:
demo - gives ml examples of features
- help - explains any function; help help explains how help works
- lookfor searches help
- doc is documentation page
- quit or exit to exit ml
Files saved under the current folder section
- semicolon at end of statement suppresses the output
namelengthmax gives the max variable length
- who shows the defined variables
- whos shows the vars and other info about them
- clear clears all vars
- clear varname clears a specific var
vars stored as types
- groups of types are called classes
- floats are numbers c decimal places, and can be single or double (precision), where double can store larger numbers than single
- integers can be type: int8, int32 or int 64, which vary on the amt of info each int var stores (int8 uses 8 bits)
- one bit is used for the sign (pos or neg)
-- unsigned int types (uint8, uint16, uint32, uint64) does not store a sign and can only be pos
- numbers stores as type double by default
- the range of a type shows the smallest and largest numbers that can be stored (uint8 can store 0-255 bc has 2^8 or 256 integers
- to find the range of a type, use: intmin() or intmax()
- type char stores characters or strings
- logical stores T/F
- type casting is converting from one type to another, ie:
>> van = 3 + 3
>> vani = int8(van)
- class() shows the var type
- numbers displayed c 4 decimal pts by default, which can be made longer c long (15 decimals) or short (the default of 4); using format: >> format long
- format can also change spacing from loose (default) or compact: >> format compact
- long expressions carried onto next line by the ellipsis or continuation operator, which is 3 or more dots: ...
Unary operators work a single val or operand and binary operators which operate 2+ vals / operands
- ie., "-" is unary for negation, binary for subtraction
- e used for exponential notation: >>2e4 ans = 20000
(same as >>2 * 10^4)
- ml uses standard order of operations
- elfun is another way to show help topics
- rem and mod return remainder from division
-- ie >>rem(13.5) ans = 3
- sign returns 1 if ans pos, 0 if neg
- fix rounds elements of var to nearest int towards 0
- floor rounds towards minus infinity
- ceil rounds towards plus infinity
- round goes to nearest integer
- sqrt for the squareroot, nthroot to find the nth root
- sin is sine function in radians, arcsine is asin, sinh is the hyperbolic sine, and sind is degrees not radians
- i or j is the sqrt(-1)
- inf is infinity; NaN is not a number, like 0/0
- e or e^1 is equivalent to exp(1)
Random Numbers
- seed is predetermined val or from the comps clock that determines random numbers
- rand generates uniformly distributed random real numbers
- rng used to set the initial seed, ie >>rng('shuffle')
- rng('default') gets back to original seed ( 0 )
- >>rand*10 generates random int in interval 0-10
- to make rand int from 0-10: >> round(rand*10)
- make a rand int in range 20-35:
>> low = 20
>> high = 35
>> round(rand*(high-low)+low)
# ie. round(rand*range+lowerLimit)
Characters
- must be in quotes, or interpreted as var (ie 'x')
- can convert char to ASCII code (>> int32('a') = 97
- char() converts numbers to chars, ie char(97) = a
- numbers are displayed indented, chars are left align
- thus chars can be manipulated like numbers:
>>'a' +1 = 98 >> char('a' +2) = c
Relational / Boolean / logical expressions are either T/F
- relational operators are < > <= >= == ~=
- true is 1, false is 0 in the logical class
- can compare chars using their ASCII vals
- || or, && and, ~ not
-- not (~) is unary operator, others are binary
-- || and && are short-circuit operators (if the result of the expression can be determined based on the first part of the expression then the second part won't be eval'd
- xor(,) returns a logical true if one and only one of the arguments is true, and false if >1 is true
- relational operators are lower on order of operations than most other stuff
- examples:
>> 3==5+2 ans=0
>> 'b' < 'a' +1 ans = 0
>> 10>5+2 ans = 1
>> (10>5)+2 ans = 3
>> 'c' == 'd' - 1 && 2 < 4 ans = 1
>> 'c' == 'd' - 1 || 2 > 4 ans =1
>> xor('c' == 'd' - 1, 2 > 4) ans = 1
>> xor('c' == 'd' - 1, 2 < 4) ans = 0
>> 10 > 5 > 2 ans = 0
Exercises
1. >> weight_cu = 63.55
2. >> myage = 30 >>myage = myage - 2
3. >> namelengthmax ans = 63
4. >>lbs = 190 >> whos
5. >> intmin('uint32') ans = 0 ... intmax('uint32') ans = 4.295e+09
>> intmin('uint64') ans = 0 ... intmax('uint64') ans = (2^64) 1.8e19
6. >> vart = 34.34 >> virt = int32(vart)
7. Integer type ranges, c prediction (pred) and actual (act) values, for intmax (intmin for all int = -(2^n/2), for all uint= 0 )
Pred. Act. Pred. Act.
int8 (2^8) / 2 - 1 = 127 uint8 2^8 -1 = 255
int16 (2^16) /2- 1 = 32767 uint16 2^16 -1 = 65535
int32 (2^32)/2-1 = 2.15e9 uint32 2^32 -1 = 4.3e9
int64 (2^64)/2-1 9.2e18 uint64 2^64 -1 = 1.8e19
8. help format # some highlights
format does not affect how MATLAB computations are done.
format SHORTE Floating point format with 5 digits.
format HEX Hexadecimal format.
format BANK Fixed format for dollars and cents.
9. >> format RAT Approximation by ratio of small integers. Numbers with a large numerator or large denominator are replaced by *
>> 5/16 + 2/7 = 67/112
10. Evaluate and enter to ml
25 / 5 *5 = 25
4 + 3 ^ 2 = 13
(4 + 3) ^ 2 = 49
3 / 12 + 5 = 5.25
4 - 2 * 3 = -2
11. lbs to kilos
>> pounds = 10
kilos = pounds / 2.2
12. >> ftemp = 100
ctemp = (ftemp - 32) * (5 / 9) = 37.7778
13. gallon = 1
cups = gallon * 16
14. sin (sine of angle in radians) and sind (degrees)
>> sind(90)
sin(pi / 2)
15. Resistors in parallel
>> r1 = 1
r2 =1
r3 = 1
total = 1 / ((1 / r1) + (1 / r2) + (1 / r3))
16. help elfun - elementary math functions
>> fix(3.5) and floor(3.5) = same
fix(3.4) and fix(-3.4) = different
fix(3.2) and floor(3.2) = same
fix(-3.2) and floor(-3.2) = diff (-4 vs -4)
fix(-3.2) and ceil(-3.2) = same
17. round = floor if decimal 0 - 0.4; round = ciel if decimal 0.5-0.9)
18. help
rem = remainder after division
mod = modulus (signed remainder after division)
19. >> sqrt(19)
3^12
tan(pi)
20. Random generation
>> rand*20
>> rand*30+20
>>round(rand*9+1)
>> round(rand*10)
>> round(rand*50+50)
21. Change seed
>> rng("shuffle")
22. Which comes first, capitals or lowercase in ASCII?
>> int32('a')
>>int32('A')
23. Shift xyz
>> char('xyz'+2)
24. >>'b' >= 'c' - 1 ans = 1
>> 3 == 2 +1 ans = 1
>> (3 == 2) + 1 ans = 1
>> xor(5 < 6, 8 > 4) ans = 0
25. >> xor(x>5, y<10)
26. 3*10^5 == 3e5
27. log10(10000)
28. help! intmin and intmax for real #'s? realmin and realmax
29.
30. Lorentz factor
>> c = 3e8
v = rand*3e8
l = 1/(sqrt(1-((v^2)/(c^2))))
31. Weight manufacturing
>> w = rand
N = 2
low =
32. Cost of Containment
r = rand*50+50
>> C = (32430/r) + (428 * pi * r)
33. Chemicals
34. geometric mean
>> nthroot(1.15*1.5*1.3, 3)
Vectors and Matrices
Store data of the same type; MATLAB short for MATrix LABoratory
- vector can be row (1 x n) or column (n x 1) vector
-- vectors same as 1-D array in other languages (thus can call its use an array operation)
-- scalars have 1 x 1 dimensions (one value)
- matrix has r x c dimensions
Create a Row Vector
- put in [ ] square brackets separated by space or comma
>> k = [4 5 6 7]
>> k = [4,5,6,7] ## same thing
- colon mark : or colon operator used to iterate stuff
>> itr = 1:5 itr = 1 2 3 4 5
-- adding another colon mark changes to step value
>> itr = 1:3:10 itr = 1 4 7 10
>> vec = 9:-2:1 vec = 9 7 5 3 1
- linespace(x,y,n) makes linearly spaced vector c n values in range x to y
>> ls = linspace(1,49,7) ls = 1 9 17 25 33 41 49
-- similarly, logspace(x,y,n) makes logarithmically spaced vector from 10^x to 10^y c n values
>> ls = logspace(1,6,6) ls = 10 100 1000 ... 10000 100000 1000000
- transpose operator ( ' )
>> x=x'
x =
1.0000
3.2500
5.5000
7.7500
10.0000
can create automatically as column vector by transposition: for column vector starting at 5 ending at 9, spaced by 2 elements:
>> x=(5:2:9)'
x =
5
7
9
5x5 matrix of random numbers:
> x=rand(5)
x =
0.8147 0.0975 0.1576 0.1419 0.6557
0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 0.8491
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
5 row, 1 column of rand numbers:
>> x=rand(5,1)
x =
0.7577
0.7431
0.3922
0.6555
0.1712
zeros function:
>> x=zeros(6,3)
x =
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
- vector variables can be created using existing vars, called vector concatenation:
>> newVec = [vec ls]
newVec =
Columns 1 through 10
9 7 5 3 1 10 100 1000 10000 100000
Column 11
1000000
- each element number called index or subscript.
-- start at 1, can access index by using vector name c ( )
>> newVec(2) ans = 7
-- above pronounced: "newVec sub 2"
Saving variable data to file datafile.mat
>> save datafile.mat data
clear
> load datafile.mat
get value from 6th row 3rd column, data is the name of a 7x4 matrix:
>> v=data(6,3)
v =
9.0698
end can be used to get to the last row or column:
>> v=data(end, 3)
v =
5.3002
can use arithmetic c end:
>> p=data(end-1,3)
p =
9.0698
to get the last 2 columns of matrix data:
>> volumes=data(:,3:4)
volumes =
4.0753 NaN
6.6678 2.1328
1.5177 3.6852
3.6375 8.5389
4.7243 10.1570
9.0698 2.8739
5.3002 4.4508
to get the 6th element from the vector density:
>> p=density(6)
p =
6.1100
can select a subset of a vector:
>> p=density(2:5)
p =
1.7800
0.8600
1.6000
3.0000
to change a variable combining indexing and assignment:
>> v2(1)=0.5
v2 =
0.5000
2.1328
3.6852
8.5389
10.1570
2.8739
4.4508
Performing Array Ops on Vectors
- add 1 to each element of v1
>> r=v1+1
r =
5.0753
7.6678
2.5177
4.6375
5.7243
10.0698
6.3002
- can combine vectors of the same size
>> vs = v1+v2
vs =
4.5753
8.8006
5.2029
12.1764
14.8813
11.9437
9.7510
- can multiply array by a scalar
> va = vs/2
va =
2.2877
4.4003
2.6014
6.0882
7.4406
5.9718
4.8755
- max() can extract the max val of a vector:
>> vm = max(va)
vm =
7.4406
- can perform math ops on vecs:
>> vr=round(va)
vr =
2
4
3
6
7
6
5
- the * does matrix mult, while the .* does elementwise multiplication
> mass = density.*va
mass =
1.2125
7.8325
2.2372
9.7411
22.3220
36.4880
12.3838
Multiple Outputs from Function Calls
- dsize has the size of the data variable
>> dsize = size(data)
dsize =
7 4
- can use [ ] to extract single or double output vars:
>> [dr,dc] = size(data)
dr =
7
dc =
4
- can use max() to get the max val c corresponding index val and assign it to vars
>> [vMax, ivMax] = max(v2)
vMax =
10.1570
ivMax =
5
- to create matrix c 5 rows, 7 columns c random ints from 1 to 20:
>> x=randi(20,5,7)
x =
14 5 5 2 1 1 18
3 1 15 18 20 18 19
20 8 8 20 7 14 1
10 5 4 19 15 16 2
18 17 15 9 8 12 5
Plotting Vectors
>>plot(x, y)
- can changes plot styles, such as to change to red star makers with no line can use:
> plot(sample, mass2, 'r*')
- can plot graphs on top of each other c the hold on command:
>> hold on
- use hold off to go back to default of writing over (and deleting) graphs if made sequentially
- close alll command closes the figure window
- if plot single vector by itself, matlab uses the nth element as the x-axis in the plot
- plot can accept vars that have assoc vals:
>> plot(v1,'Linewidth',3)
- can also plot after other stuff:
> plot(sample, v1, 'ro', 'LineWidth', 4)
- give it a title() !
>> title('Sample Densities')
- labelling the y-axis
>> ylabel('Density (g/cm^3)')
- can select the var names in the workspace to plot against one another
Project: Electricity Usage
Will plot e use in diff sectors (res, com, ind)
- residential highest, then commercial and industrial
>> load electricity.mat
>> usage #shows the values in usage
## change an NaN val in row 2 col 3
>> usage(2,3)=2.74
## create variable res that has the first column of usage
>> res = usage(:,1)
## create variable comm that has the 2nd column of usage
>> comm = usage(:,2)
## for industrial
ind = usage(:,3)
## Create column vector for years 1991 to 2013
>> yrs = (1991:2013)'
## plot res against yrs c blue dashed line
>> plot(yrs, res, 'b--')
>> hold on ## place hold on to add graph on top
>> plot(yrs, comm, 'k:') ## commercial in blk dotted ln
>> plot(yrs, ind, 'm-.') ## industrial, magenta dash-dot
>> title('July Electricity Usage') ## Add title
>> legend('res', 'comm', 'ind') ## Add legend
Project: Audio Frequency
Will create a signal that has the beat phenomenon (2 signals close together causes amplitude pulse) by analyzing the signal's freq content
% create var fs for sampling freq of audio signal
>> fs = 10
>> t=0:1/fs:20; ## t is times audio sampled, is a vector from 0 to 20 in interval of 1/fs
% y is sum of 2 sine waves
>> y=sin(1.8*2*pi*t)+sin(2.1*2*pi*t);
>>plot(t,y)
% the Fourier transform, which gives info about the freq content of the signal
>> yfft = fft(y)
% makes var with numel() function, which returns # elements in array
>> n = numel(y)
>> f=0:fs/n:fs*(n-1)/n ## makes vec f
% need abs() to plot Fourier transform values which are complex numbers
>> plot(f, abs(yfft))
% the spikes on the left side of plot are freqs of 2 sine wives creating the beat phenomenon when close together
% there are 4 spikes b/c of the Nyquist freq, which is 5, or fs/2, here. When input vals are real numbers, fft function always returns data c magnitude symmetric around the Nyquist freq (the 2nd half of plot is a mirror image of 1st half)
Go to new script to create new script. Running programs will save it before execution
Can run MATLAB scripts from command line by typing in the name of the script
Logical Ops and Vars
%Is pi greater than 3? (1=true)
- can compare vectors to each other
% Create logical array as array index, where matlab extracts array elements where index is true
>>v = v1(v1<4)
% can use logical indexing to replace vals in array, to replaces vals in v1 that are greater than 5 with 10:
>> v1(v1>5) = 10
Flow Control
Control whether code is executed c if statement, that is finished with the end statement, ex:
% Calculate A
A = randn(1)
% Calculate B only if A is greater than 0
if A>0
B = sqrt(A)
else
B=0
end
% for Loop, inc idx by 1 from 1 to 5
% Calculate x
x = (11:15).^2;
% TODO - wrap the line below in a for loop
for idx=1:5
disp(x(idx))
end
Stellar Motion
Use ML to find observed wavelength of star and compare to canonical value to see if blue or red shifted (Doppler effect)
>> load starData
>> nObs = size(spectra,1);
>> lambdaStart = 630.02;
>> lambdaDelta = 0.14;
>> lambdaEnd = lambdaStart+(nObs-1)*lambdaDelta
lambdaEnd =
679.8600
% Column vector from lambda start to end in steps of lambda delta, inversed to make column vector
>> lambda = (lambdaStart:lambdaDelta:lambdaEnd)'
% each column of spectra is a different star, the 6th star is HD 94028, extract its spectra
s = spectra(:,6)
% plot spectra s as function of wavelength lambda c plot scales on both axes, with some style
>> loglog(lambda, s, '.-')
% creates 2 vars for min val of s and index where min value occurred
>> [sHa, idx] = min(s)
% use idx to index into lambda to find wavelength of Hydrogen-alpha line, stored as lambda Ha
>> lambdaHa = lambda(idx)
% plot single point as red square
>> loglog(lambdaHa, sHa, 'rs', 'Markersize', 8)
% Redshift factor, to determine speed of star relative to Earth
>> z = (lambdaHa/656.28)-1
% multiplying redshift factor by speed of light, can calculate speed of star relative to Earth
>> speed = z*3e5
Building a Discrete LTI System
1. Solve for most recent sample [y]n
2. Add Delay blocks
3. Construct right-hand side of eqn
4. Set initial conditions and define constants
dspstartup in MATLAB command lets you automatically configure settings for the ML session
References
1.