Upload
others
View
11
Download
0
Embed Size (px)
Citation preview
MATLABExamples
Hans-PetterHalvorsen,M.Sc.
Mathematics
MathematicswithMATLAB
• MATLABisapowerfultoolformathematicalcalculations.• Type“helpelfun”(elementarymathfunctions)intheCommandwindowformoreinformationaboutbasicmathematicalfunctions.
MathematicsTopics
• BasicMathFunctionsandExpressions𝑧 = 3𝑥% + 𝑥% + 𝑦%� + 𝑒+,(.)
• Statistics– mean,median,standarddeviation,minimum,maximumandvariance
• TrigonometricFunctionssin() , cos() , tan()
• ComplexNumbers𝑧 = 𝑎 + 𝑗𝑏
• Polynomials𝑝 𝑥 = 𝑝<𝑥= + 𝑝%𝑥=>< + ⋯+ 𝑝=𝑥 +𝑝=@<
BasicMathFunctions
Createafunctionthatcalculatesthefollowingmathematicalexpression:
𝑧 = 3𝑥% + 𝑥% + 𝑦%� + 𝑒+,(.)
Wewilltestwithdifferentvaluesfor𝑥 and𝑦
function z=calcexpression(x,y)
z=3*x^2 + sqrt(x^2+y^2)+exp(log(x));
>> x=2;>> y=2;>> calcexpression(x,y)ans =
16.8284
Wecreatethefunction:
Testingthefunctiongives:
StatisticsFunctions
• MATLABhaslotsofbuilt-infunctionsforStatistics• Createavectorwithrandomnumbersbetween0and100.Findthefollowingstatistics:mean,median,standarddeviation,minimum,maximumandthevariance.
>> x=rand(100,1)*100;
>> mean(x)>> median(x)>> std(x)>> mean(x)>> min(x)>> max(x)>> var(x)
Trigonometricfunctions
sin(𝑥) cos(𝑥) tan(𝑥)
TrigonometricfunctionsItisquiteeasytoconvertfromradianstodegreesorfromdegreestoradians.Wehavethat:
2𝜋𝑟𝑎𝑑𝑖𝑎𝑛𝑠 = 360𝑑𝑒𝑔𝑟𝑒𝑠𝑠Thisgives:
𝑑 𝑑𝑒𝑔𝑟𝑒𝑒𝑠 = 𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] M180𝜋
𝑟[𝑟𝑎𝑑𝑖𝑎𝑛𝑠] = 𝑑[𝑑𝑒𝑔𝑟𝑒𝑒𝑠] M𝜋180
→Createtwofunctionsthatconvertfromradianstodegrees(r2d(x))andfromdegreestoradians(d2r(x))respectively.Testthefunctionstomakesurethattheyworkasexpected.
function d = r2d(r)
d=r*180/pi;
Thefunctionsareasfollows:
function r = d2r(d)
r=d*pi/180;
>> r2d(2*pi)ans =
360>> d2r(180)ans =
3.1416
Testingthefunctions:
Trigonometricfunctions
Givenrighttriangle:
• CreateafunctionthatfindstheangleA(indegrees)basedoninputarguments(a,c),(b,c)and(a,b)respectively.
• Use,e.g.,athirdinput“type”todefinethedifferenttypesabove.• Useyourpreviousfunctionr2d() tomakesuretheoutputofyourfunctionisindegreesandnotinradians.
• Testthefunctionstomakesureitworksproperly.
Trigonometricfunctions
Wehavethat:
sin 𝐴 =𝑎𝑐 , 𝐴 = 𝑎𝑟𝑐𝑠𝑖𝑛
𝑎𝑐
cos 𝐴 =𝑏𝑐 , 𝐴 = 𝑎𝑟𝑐𝑐𝑜𝑠
𝑏𝑐
tan𝐴 =𝑎𝑏 , 𝐴 = 𝑎𝑟𝑐𝑡𝑎𝑛
𝑎𝑏
ThePythagoras'theorem:𝑐% = 𝑎% + 𝑏%
function angleA = right_triangle(x,y, type)
switch typecase 'sin'
angleA=asin(x/y);case 'cos'
angleA=acos(x/y);case 'tan'
angleA=atan(x/y);end
% Convert from radians to degreesangleA = r2d(angleA);
Thefunctionbecomesasfollows:
Testingthefunction:>> a=5a =
5>> b=8b =
8>> c=sqrt(a^2+b^2)c =
9.4340>> right_triangle(a,c,'sin')ans =
32.0054>> right_triangle(b,c,'cos')ans =
32.0054>> right_triangle(a,b,'tan')ans =
32.0054
Lawofcosines
Given:
Createafunctionwhereyoufindcusingthelawofcosines.
𝑐% = 𝑎% + 𝑏% − 2𝑎𝑏𝑐𝑜𝑠𝐶
function c = law_of_cosines(a,b,C)
c = sqrt(a^2 + b^2 - 2*a*b*cos(C));
Thefunctionbecomesasfollows:
Testingthefunction:>> a=2;, b=3;, C=pi;,
>>law_of_cosines(a,b,C)ans =
5
PlottingTrigometricfunctions
• Plot𝑠𝑖𝑛(𝜃)and𝑐𝑜𝑠(𝜃) for0 ≤ 𝜃 ≤ 2𝜋 inthesameplot.• Makesuretoaddlabelsandalegend,andusedifferentlinestylesandcolorsfortheplots.
clf
x=0:0.01:2*pi;
plot(x, sin(x), 'c+:')hold on
plot(x, cos(x), 'r:')hold off
legend('sin', 'cos')xlabel('x')ylabel('f(x)')
% Define x-valuesx=0:0.01:2*pi;
% subplot 1subplot(2,1,1)plot(x, sin(x))title('Plotting sin(x)')xlabel('x')ylabel('sin(x)')
% Subplot 2subplot(2,1,2)plot(x, cos(x))title('Plotting cos(x)')xlabel('x')ylabel('cos(x)')
OrwecanuseSubplots:
clf
x=0:0.01:2*pi;
plot(x, sin(x), x, cos(x))
AComplexNumberisgivenby:
𝑧 = 𝑎 + 𝑗𝑏Where
𝑗 = −1�
Wehavethat:𝑎 = 𝑅𝑒 𝑧
𝑏 = 𝐼𝑚(𝑧)
ComplexNumbers
𝑧 = 𝑎 + 𝑗𝑏
0 𝑎
𝑏
𝐼𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦𝐴𝑥𝑖𝑠(𝐼𝑚)
𝑅𝑒𝑎𝑙𝐴𝑥𝑖𝑠(𝑅𝑒)
ComplexNumbersPolarform:
𝑧 = 𝑟𝑒\]
Where:𝑟 = 𝑧 = 𝑎%+𝑏%�
𝜃 = 𝑎𝑡𝑎𝑛𝑏𝑎
Note!
𝑎 = 𝑟 cos 𝜃
𝑏 = 𝑟 sin 𝜃
𝑧 = 𝑟𝑒\]
0 𝑎
𝑏
𝐼𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦𝐴𝑥𝑖𝑠(𝐼𝑚)
𝑅𝑒𝑎𝑙𝐴𝑥𝑖𝑠(𝑅𝑒)
𝜃𝑟
𝑗 = −1�
ComplexNumbersRectangularform ofacomplexnumber Exponential/polarform ofacomplexnumber
Length(“Gain”): Angle(“Phase”):
1 2
𝑧 = 𝑎 + 𝑗𝑏
0 𝑎
𝑏
𝐼𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦𝐴𝑥𝑖𝑠(𝐼𝑚)
𝑅𝑒𝑎𝑙𝐴𝑥𝑖𝑠(𝑅𝑒)
𝑧 = 𝑟𝑒\]
0 𝑎
𝑏
𝐼𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦𝐴𝑥𝑖𝑠(𝐼𝑚)
𝑅𝑒𝑎𝑙𝐴𝑥𝑖𝑠(𝑅𝑒)
𝜃𝑟
𝑟 = 𝑧 = 𝑎% + 𝑏%� 𝜃 = 𝑎𝑡𝑎𝑛𝑏𝑎
𝑗 = −1�
Rectangularform→Exponential/polarform
Giventhecomplexnumbers(Rectangularform):𝑧 = 𝑎 + 𝑗𝑏
Exponential/polarform:𝑧 = 𝑟𝑒\]
Where𝑟 = 𝑧 = 𝑎% + 𝑏%�
𝜃 = 𝑎𝑡𝑎𝑛𝑏𝑎
z = a + bjr = sqrt(a^2 + b^2)
z = a + bjtheta = atan(b/a)
z = a + bjr = abs(z)
z = a + bjtheta = angle(z)
or:
or:
Rectangularform→Exponential/polarformclearclc
a = 5;b = 3; % Rectangular Form:z = a + b*i % Polar Form:r = sqrt(a^2 + b^2)r = abs(z) theta = atan(b/a)theta = angle(z)
z = r*exp(j*theta)
𝑧 = 5 + 𝑗3
𝑧 = 5 + 𝑗3
𝑧 = 𝑟𝑒\] = 5.83𝑒\`.ab
ComplexNumbers
Toaddorsubtracttwocomplexnumbers,wesimplyadd(orsubtract)theirrealpartsandtheirimaginaryparts.Giventhecomplexnumbers:
𝑧< = 𝑎< + 𝑗𝑏<and𝑧% = 𝑎% + 𝑗𝑏%Addition:
𝑧c = 𝑧< + 𝑧% = 𝑎< + 𝑎% + 𝑗 𝑏< +𝑏%Subtraction:
𝑧c = 𝑧< −𝑧% = 𝑎< − 𝑎% + 𝑗 𝑏< −𝑏%
ComplexNumbers
InDivisionandmultiplication,weusethepolarform.
Giventhecomplexnumbers:𝑧< = 𝑟<𝑒\]d and𝑧% = 𝑟%𝑒\]e
Multiplication:
𝑧c = 𝑧<𝑧% = 𝑟<𝑟%𝑒\(]d@]e)Division:
𝑧c =𝑧<𝑧%=𝑟<𝑒\]d𝑟%𝑒\]e
=𝑟<𝑟%𝑒\(]d>]e)
ComplexNumbers– MATLABFunctionsFunction Description Example
i,j Imaginaryunit.AsthebasicimaginaryunitSQRT(-1),iandjareusedtoentercomplexnumbers.Forexample,theexpressions3+2i,3+2*i,3+2j,3+2*jand3+2*sqrt(-1)allhavethesamevalue.
>>z=2+4i
>>z=2+4j
abs abs(x)istheabsolutevalueoftheelementsofx.Whenxiscomplex,abs(x)isthecomplexmodulus(magnitude)oftheelementsofX.
>>z=2+4i
>>abs(z)
angle Phaseangle.angle(z)returnsthephaseangles,inradians >>z=2+4i
>>angle(z)
imag Compleximaginarypart.imag(z)istheimaginarypartofz. >>z=2+4i
>>b=imag(z)
real Complexrealpart.real(z)istherealpartofz. >>z=2+4i
>>a=real(z)
conj Complexconjugate.conj(x)isthecomplexconjugateofx. >>z=2+4i
>>z_con=conj(z)
complex Constructcomplexresultfromrealandimaginaryparts.c=complex(a,b)returnsthecomplexresultA+Bi
>>a=2;
>>b=3;
>>z=complex(a,b)
ComplexNumbers
Giventwocomplexnumbers𝑐 = 4 + 𝑗3, 𝑑 = 1 − 𝑗
FindtherealandimaginarypartofcanddinMATLAB.→UseMATLABtofind𝑐 + 𝑑, 𝑐 − 𝑑, 𝑐𝑑𝑎𝑛𝑑𝑐/𝑑.UsethedirectmethodsupportedbyMATLABandthespecificcomplexfunctionsabs,angle,imag,real,conj,complex,etc.togetherwiththeformulasforcomplexnumbers.→Findalso𝑟 and𝜃.Findalsothecomplexconjugate.
c=5+3i;d=1-i;
disp('c+d')%Directly-----------------z = c + d%Manually-----------------z_real = real(c) + real(d);z_imag = imag(c) + imag(d);z = complex(z_real,z_imag)
% r and angle + complex conungater=abs(z)theta=angle(z)complconj=conj(z)
disp('c-d')%Directly--------------z = c - d%Manually--------------z_real = real(c) - real(d);z_imag = imag(c) - imag(d);z = complex(z_real,z_imag)%or: z = z_real + z_imag*i
disp('c*d')%Directly-------------z = c*d%Manually-------------z_abs = abs(c)*abs(d);z_angle = angle(c) + angle(d);z_real = z_abs*cos(z_angle);z_imag = z_abs*sin(z_angle);z = complex(z_real,z_imag)
disp('c/d')%Directly-------------z = c/d%Manually-------------z_abs = abs(c)/abs(d);z_angle = angle(c) - angle(d);z_real = z_abs*cos(z_angle);z_imag = z_abs*sin(z_angle);z = complex(z_real,z_imag)
c+dz =
6.0000 + 2.0000iz =
6.0000 + 2.0000ir =
6.3246theta =
0.3218complconj =
6.0000 - 2.0000ic-dz =
4.0000 + 4.0000iz =
4.0000 + 4.0000ic*dz =
8.0000 - 2.0000iz =
8.0000 - 2.0000ic/dz =
1.0000 + 4.0000iz =
1.0000 + 4.0000i
Thisgives:
ComplexRoots
Findtherootsoftheequation:𝑥% + 4𝑥 + 13
Therootsaregivenby:𝑥% + 4𝑥 + 13 = 0
FindalsotheSumandDifferenceoftheroots.
a=1;b=4;c=13;
solveeq(a,b,c)
Wecane.g.,usethesolveeq functionwecreatedinapreviousexample:function x = solveeq(a,b,c)if a~=0
x = zeros(2,1);x(1,1)=(-b+sqrt(b^2-4*a*c))/(2*a);x(2,1)=(-b-sqrt(b^2-4*a*c))/(2*a);
elseif b~=0x=-c/b;
elseif c~=0disp('No solution')
elsedisp('Any complex number is a solution')
end
a=1;b=4;c=13;
p=[a,b,c]roots(p)
Orwecanusetheroot function:
Note!thesolutioniscomplexconjugate.
Thesumoftwocomplexconjugatenumbersisalwaysreal.Inourcase:ans =
-4
Whilethedifferenceisimaginary(norealpart).ans =
0 + 6.0000i
Polynomials
Apolynomialisexpressedas:𝑝 𝑥 = 𝑝<𝑥= + 𝑝%𝑥=>< + ⋯+ 𝑝=𝑥 +𝑝=@<
where𝑝<, 𝑝%, 𝑝c, … arethecoefficientsofthepolynomial.
Exampleofpolynomial:𝑝 𝑥 = −5.45𝑥b + 3.2𝑥% + 8𝑥 + 5.6
PolynomialsinMATLAB
MATLABrepresentspolynomialsasrowarrayscontainingcoefficientsorderedbydescendingpowers.Example:
𝑝 𝑥 = −5.45𝑥b + 3.2𝑥% + 8𝑥 + 5.6
>> p=[-5.45 0 3.2 8 5.8]p =
-5.4500 0 3.2000 8.0000 5.8000
MATLABofferslotsoffunctionsonpolynomials,suchasconv,roots,deconv,polyval,polyint,polyder,polyfit,etc.→YoushouldlookupthesefunctionsintheHelpsysteminMATLAB.
Polynomials
DefinethefollowingpolynomialinMATLAB:
𝑝 𝑥 = −2.1𝑥b + 2𝑥c + 5𝑥 + 11
→Findtherootsofthepolynomial(𝑝 𝑥 = 0)
→Find𝑝 𝑥 = 2
Usethepolynomialfunctionslistedabove.
p = [-2.1, 2, 0, 5, 11]
roots(p)
x = 2;polyval(p,x)
MATLABCode:
p =-2.1000 2.0000 0 5.0000 11.0000
ans =2.0820
-0.0199 + 1.5193i-0.0199 - 1.5193i-1.0898
ans =3.4000
Thisgives:
𝑝 𝑥 = 2 𝑝 𝑥 = 0
Insteadofusingthepolyval()functionwecouldofcoursealsofoundtheanswerlikethis:x = 2;p = -2.1*x^4 + 2*x^3+5*x+11
Wecanusee.g.,thepolyval()functiontocheckiftheanswersarecorrect:>> x = 2.0820;>> polyval(p,x)etc.
Theanswersshallthenofcoursebe0 (oratleastaverysmallnumber).
Polynomials
Giventhefollowingpolynomials:𝑝< 𝑥 = 1 + 𝑥 − 𝑥%𝑝% 𝑥 = 2 + 𝑥c
→Findthepolynomial𝑝(𝑥) = 𝑝<(𝑥) M 𝑝%(𝑥) usingMATLABandfindtheroots→Findtherootsofthepolynomial(𝑝 𝑥 = 0)→Find𝑝 𝑥 = 2→Findthedifferentiation/derivativeof𝑝% 𝑥 ,i.e.,𝑝%i
Wewillusethepolynomialfunctionslistedabove.
Note!Thepolynomialsmayberewrittenas:
𝑝< 𝑥 = −𝑥% + 𝑥 + 1𝑝% 𝑥 = 𝑥c + 0𝑥% + 0𝑥 + 2
P1 = [-1, 1, 1];P2 = [1, 0, 0, 2];
p = conv(p1,p2)
r = roots(p)
polyval(p,2)
TheMATLABcodebecomes:Thisgives:
p =-1 1 1 -2 2 2
r =1.6180 0.6300 + 1.0911i0.6300 - 1.0911i-1.2599 -0.6180
ans =-10
ThePolynomialbecomes:
𝑝 𝑥 = −𝑥a + 𝑥b + 𝑥c − 2𝑥% + 2𝑥 + 2
PolynomialFitting
Findthe6.orderPolynomialthatbestfitsthefollowingfunction:𝑦 = sin(𝑥)
→Plotboththefunctionandthe6.orderPolynomialtocomparetheresults.
x=0:0.1:2*pi;y=sin(x);
figure(1)plot(x,y)
% Finding a 6. order polynomialp=polyfit(x,y,6)
y2=polyval(p,x);
figure(2)plot(x,y2)
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:[email protected]:http://home.hit.no/~hansha/