




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、and its application inEngineeringAssoc. Prof. Kirin Shi施圣賢上海交通大學(xué)機械與動力Review on Lecture 2 Data type Data input/output Logical operation Script & Function fileInput data from a filecommand:eval_varable = load('filename', '-mat', 'variables') eval_varable = load('filenam
2、e', '-ascii') eval_varable = dlmread('filename', delimiter, range)>> load('C:>> load('C:>> load('C:>> dlmread('C:_course example2_0.mat','-mat','a')_courseexample2_0.mat','-mat')_courseexample2_1.dat',
3、39;-ascii')_courseexample2_2.dat', ' ', 4,0,10,3)imreadOutput data to a filecommand:eval_varable = save('filename', 'variables', 'format')fileID = fopen(filename, permission)Output data to a filecommand:eval_varable = save('filename', 'variables
4、9;, 'format')Output data to a filecommand:fileID = fopen(filename, permission) fprintf(fileID, format, A, .)Output data to a fileExample:data1=1;2;3;4;data2=5;6;7;8; data3=9;10;11;12;result=data1,data2,data3;file_head = 'This is an example for fprint fopen command'fid = fopen('C:
5、_courseexample2_3.dat', 'wt+');fprintf(fid, '%s n', file_head, 'VARIABLES = "X""Y""Z"');row,col = size(result); for i= 1:rowfor j= 1:col-1fprintf(fid, '%ft', result(i, j);endfprintf(fid, '%fn', result(i, col); endfclose(fid);i
6、mwrite, fwrite, fscanf, fread, fgetl, fgetsLogical operatorcommand:and|ornot&&&allDetermine whether all array elements are nonzero or trueany Determine whether any array elements are nonzeroxor Logical exclusive-ORC=xor(A,B)>>a=1,2,3;0,1,1;1,0,0>> all(a)>> all(a,2)>&
7、gt; any(a)>> any(a,2)>> a=1,2,3>> b=0,4,0>> a && b>> a & bRelational operatorcommand:larger equallarger or equal>=>=<=<=smallernot equal smaller or equal>> a=1,2,3>> b=0,4,0>> a > b>> a < b>> a=1,2,3;4,5,6;7,8,
8、9>> b=a>3>> c=a(a>3)>> d=a=6Programs: definitionProgram: sequences of commands which arestored infiles. These files must have the extension .m (e.g. filename.m) and that is why they are called M-files.An M-file is executed by typing its name (withoutthe extension .m) at the p
9、rompt. This would be equivalent to typing all thecommands in the file at the prompt one by one, in the order they have beenwritten.Different types of M-filesM-files are of two types: Script files and function files. Script files are just collections ofstatements that are stored ina file.Script files
10、 do not have clearly defined input and output arguments. A function file receives data throughinput arguments, and return results through output arguments.Script FilesQuite often you want to reuse bits of codes over again.One way to do this is to use a script file.A script file is a collection ofcom
11、mands which are saved in a file rather thanbeing typed at theprompt one by one.Example: body mass index of an individual>> height = 1.7;>> weight = 70;>> body_mass_index = weight/height2body_mass_index =24.2215Example of a script fileOpen an Edit/debug window and then type the foll
12、owing statements in it.%Program to calculate the body mass index of a%The's height in metersheight = 1.70;%Theweight = 70;'s weight in Kilograms%calculate the body mass indexbody_mass_index = weight/height2Running a script fileTo run your program, type its name at the command prompt without
13、the extension .m.Make sure the name of the program is not the same as the name of a variable you have used or the name of a variable in your program.>> bodymassindexbody_mass_index = 24.2215Changing data in your script fileTo change the weight and height of the individual, open the file contai
14、ning your code(bodymassindex.m) and change the height and weight to, for example, 1.80m and 86kg.Then run the program again.>> bodymassindex body_mass_index =26.5432Function files inIn, functions behave in the same wayas the foregoing algebraic function.For example, we can write a function fil
15、e to calculate the body mass index of an individual in the following way:Function file: an examplefunction bmi = bodymassindex(height, weight)%Program to calculate the body mass index%Two input arguments:%the first one is height in meters%the second one is weight in kilograms%the only output is the
16、body mass index (bmi)%Last revision: 2 October 2010%Example: my_bmi = bodymassindex(1.81,91)%calculate the body mass indexbmi = weight/height2;Running a function fileNow type the following command and see the result>> my_bmi = bodymassindex(1.81,91) my_bmi =27.7769function bmi = bodymassindex(
17、height, weight)bmi = weight/height2;Function file: input argumentsYou can choose any values for the input arguments.So if you are 1.65m tall and your weight is 55kg, then your body mass index can be calculated by the following command>> my_bmi = bodymassindex(1.65,55) my_bmi =20.2020Giving val
18、ues to input argumentsYou can assign the height and weight values tovariables and then use these variables as input arguments. For example,>> my_height = 1.65; my_weight = 55;>> my_index = bodymassindex(my_height,my_weight)my_index =20.2020function bmi = bodymassindex(height, weight)bmi
19、= weight/height2;The workspace of a functionThe workspace is an area in computer memory where variables are stored.A script file does not have an independent work space.A function file has its own independent (private) workspace. In other words, the variables inside a function file are all local var
20、iables,whose values are stored in a separateplace fromworkspace.The workspace of a function>> my_bmi = bodymassindex(1.81,91) my_bmi =27.7769>> bmi? Undefined function or variable 'bmi'.communicates with a function only through its input and output arguments.function bmi = bodyma
21、ssindex(height, weight)bmi = weight/height2;Quick exerciseWrite a function file called exp1.m to calculate the sum, mean,and minimum of a set of value y, which is defined according to theumfollowing equation. Then construct a new array y_positive with positivevalues of y1+ sin( 1 𝑥)𝑦
22、 = 𝑥3 +1 12𝜋𝑥Input: x: 3, -2, 0.5, 1.2Output: y_sum, y_max, y_min, y_mean, y_positiveExample: y_sum, y_max, y_min, y_mean,y_positive=exp1(x1, x2, x3, x4);y_sum=28.44, y_max=28.96, y_min=-7.65, y_mean=7.11y_positive=28.959529010441880,7.917826992143464Control StructuresIntrodu
23、ctionSo far in our programs, commands are executed oneafter the other in the order they have been written.Somestatements allow us to controlthe order in whichprogram are mands in aIntroductionThere are two types of control structures in:Conditional statements allow specific sections of t
24、he code to be executed or skipped based onsome logical condition.Loops cause a specific section of the code tobe executed more than once.Conditional ControlStructuresLogical operatorsFor example,5>3 is True and 2=1+3 is False. Therefore, the expression 5>3 & 2=1+3 is False.>> b = 5&g
25、t;3 & 2=1+3b =0expression Aexpression Bexpression A & BTrueTrueTrueTrueFalseFalseFalseTrueFalseFalseFalseFalseLogical operatorsFor example,5>3 is True and 2=1+5 is False. Therefore, the expression 5>3 | 2=1+5 is True.>> b = 5>3 | 2=1+5b =1expression Aexpression Bexpression A |
26、 BTrueTrueTrueTrueFalseTrueFalseTrueTrueFalseFalseFalseThe if-elseif-end structureIf (control expression 1) StatementStatementblock 1elseif (control expression 2)StatementStatement elseStatement Statementendblock 2block 3The switch-case-end structureswitch (control expression)StatementStatementcase
27、(condition 1) Statement Statementotherwise Statement Statementendblock 1block 2block 3ExampleBuying box cars for a railroad companyNo. of cars (N)Price of each car (K)N 3224 N 1020N > 1019Using if-elseif-end structurefunction cost = box_car_cost(N); Low_price = 19;Medium_price = 20;High_price = 2
28、2;if N > 10cost = Low_price * N;elseif N > 3cost = Medium_price * N;elsecost = High_price * N;endNo. of cars(N)Price of each car (K)N 3224 N 1020N > 1019Using switch-case-end structurefunction grade = score_to_grade(s);s=input(Please enter yourswitch fix(s/10)case 9grade=A+;case 8grade=A;ca
29、se 7grade=B;case 6grade=B-; otherwisegrade=C;endsocre:score=');fix: round towards zeroExampleWrite afunction to evaluate the value ofz = f(x,y) for any scalar values of x and y,where the function f(x,y) is defined as :ìx + yx 0 and y 0 x 0 and y < 0 x < 0 and y 0x < 0 and y < 0&
30、#239;x + y2ïf(x,y=)íïx+ y2ïx+ y22îX=1, y=3X=1, y=-3X=-1, y=-3function z = function_of_x_and_y(x,y) if (x>=0 & y>=0)z = x + y;elseif (x>=0 & y<0) z = x + y2;elseif (x<0 & y>=0) z = x2 + y;elsez = x2 + y2; endìx + yx 0 and y 0 x 0 and y <
31、0 x < 0 and y 0x < 0 and y < 0ïx + y2ïf(x,y=)íïïx + y2x + y22îRepetative ControlStructuresfor loop and while loop1.The for loop, which repeatedly executes a block of statements a definite number of times.The while loop, which repeatedly executes a block of stat
32、ements as long as some condition is satisfied.2.The while structure is most appropriate when thenumber of iterations in the loop is not known beforehand.General form of the for loopfor index = first:increment:laststatement statementendwhere index is called the loop variable (or the loop index).The s
33、tatements between the for statement and the end statement are referred to as the body of the loop.Make sure the index value is not changed inside theloop!General form of the while loopwhile condition statement statementendStatements will only be executed when the condition is satisfied.The statement
34、s between the while statement and the end statement are referred to as the body of the loop.Make sure the condition is changed through theexecution of statements inside the loopExample: calculate sum(xx.2) with for loopXX = 11:2:46;N_XX = length(XX);sum_of_terms = 0;for i = 1:N_XX%initialisesum_of_t
35、erms = sum_of_terms + XX(i)2;enddisp('sum of the elements of array XX squared')disp(sum_of_terms)Nested Loopsdisp('heightweightbodymassindex')for height = 1.50 : 0.10 : 1.90for weight = 50 : 10 : 90bodymassindex = weight/height2;disp(heightend endweightbodymassindex)heightweightbodym
36、assindex 22.222226.666731.111135.555640.000019.531223.437527.343731.250035.15621.50001.50001.50001.50001.50001.60001.60001.60001.60001.600050.000060.000070.000080.000090.000050.000060.000070.000080.000090.0000Example: calculate sum(xx.2) with while loopXX = 11:2:46;sum_of_terms = 0;xx=11;while xx<
37、;=46%initialisesum_of_terms = sum_of_terms + xx2;x+2;enddisp('sum of the elements of array xx squared')disp(sum_of_terms)GRAPHICSThree-dimensional line plot1510501100-1-1y (meters)x (meters)z (meters)43210212100-1-1-2-2Plotted by function surf10.502200-2-2yxzPlotted by function mesh10.502200
38、-2-2yxzPlotted by function contour21.510.50-0.5-1-1.5-2-2-10x12yPlotted by function contourf21.510.50-0.5-1-1.5-2-2-1012y2-D PLOTSCommand plot, legendplot(x1,y1,style_option_1, x2,y2,style_option2,.) x = 0:0.2:10;y1 = x.2;y2 = x.3;figure, plot(x,y1,'ko',x,y2,'r');legend('2nd orde
39、r polynomial', '3rd order polynomial')figure, axes('FontName','Times New Roman','FontSize',16);plot(x,y1,'ko',x,y2,'r*','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColo r','g','MarkerSize',10),titl
40、e('Polynomial lines','FontName','Times New Roman','FontSize',20);xlabel('X','FontName','Times New Roman','FontSize',16); ylabel('Y','FontName','Times New Roman','FontSize',16);10002nd order polynomial3rd
41、order polynomial8006004002000024 6810Command axisaxis(x_min x_max y_min ymax)x = 0:0.2:10;y1 = x.2;y2 = x.3;figure, plot(x,y1,'ko',x,y2,'r*'),legend('2nd order polynomial', '3rd order polynomial')axis(4 6 0 300) 3002nd order polynomial3rd order polynomial2502001501005
42、0044.555.56Command subplotx = 0:0.2:10;y1 = x.2;y2 = x.3;Subplot(2,2,1), plot(x,y1,'ko',x,y2,'r*'),legend('2nd order polynomial', '3rd order polynomial')Subplot(2,2,2) .Subplot(2,2,3).Subplot(2,2,4).Command subplotPlot propertiesCommand hista=1000;b=10000; xx=rand(1,2
43、500);yy=(b-a)*xx + a;hist(yy,20) xlabel('bins')% (100010,000之間正太分布的數(shù))ylabel('number of elements in each bin')title('Histogram of uniformly-distributed data with 20 bins')Histogram of uniformly-distributed data with 20 bins160140120100806040200100020003000400050006000700080009
44、00010000binsnumber of elements in each binGRAPHICSContent3-D Line plot Surface plots ContoursPretty plots based on Chaos theoryMaking movies3-D Line PLOTS3-D Line plotst = 0:0.05:15;x = exp(-0.05*t).*cos(2*t);y = exp(-0.05*t).*sin(2*t);z = t;figure, plot3 (x, y, z, '.')xlabel('x (meters)
45、');ylabel('y (meters)')zlabel('z (meters)')title('Three-dimensional line plot')Three-dimensional line plot1510501100-1-1x (meters)y (meters)z (meters)Surface PlotsSurface plotsA surface is usually defined by a function of two independentvariables;For example, functionz =
46、f(x, y) = x.2 + yFunction f is used to calculate z for each pair of (x, y) values.Therefore, to create a surface plot, we first need to generate a grid of (x, y) pointsThen find the value of z at each point of this grid.Function meshgridx y =meshgrid(xstart:xinc:xend,ystart:yinc:yend)for example,>
47、;> xx yy = meshgrid(1:1:4, 2:0.5:5);>> figure, plot(xx, yy, 'bo')>> title('Grid generated by function meshgrid', 'Fontsize',16)Coordinates of points by meshgridxx =yy =2.02.53.03.54.04.55.011111112222222333333344444442.02.53.03.54.04.55.02.02.53.03.54.04.55.02.
48、02.53.03.54.04.55.0Grid generated by function meshgrid54.543.532.5211.522.533.54Function surft1 = -2:0.1:2;t2 = -2:0.1:2;x y = meshgrid(t1, t2);z = (x.2) + (y.2) -0.5*(x.2).*(y.2); figure, surf(x,y,z)Function surfFunction meshFunction mesh creates a surface which has a wire-frameappearance.Function
49、surf creates a surface which looks more like a real surface.t1 = -2:0.1:2;t2 = -2:0.1:2;x y = meshgrid(t1,t2);z = exp(-0.5*(x.2 + y.2); figure, mesh(x,y,z)ContoursFunction contour contourffigure, contour (x, y, z, 0.1:0.1:1.9)axis squarexlabel('x', 'Fontsize',14),ylabel('y', 'Fontsize',14) title('Plotted by function contour','Fontsize',14)Plotted by function contour21.510.50-0.5-1-1.5-2-2-10x12yPlotted by function contourf21.510.50-0.5-1-1.5-2
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 二零二五年度房屋租賃合同安全事故應(yīng)急響應(yīng)及責(zé)任書
- 二零二五年度私企員工私下股份獎勵分配協(xié)議
- 2025年度茶館店鋪合租合作協(xié)議
- 二零二五年度生態(tài)旅游區(qū)租院子管理服務(wù)合同
- 2025年度特種承攬項目增值稅稅率明確協(xié)議
- 二零二五年度養(yǎng)羊產(chǎn)業(yè)風(fēng)險管理與保險合作協(xié)議
- 2025年度新能源汽車購置貸款合同
- 二零二五年度房屋租賃合同租賃保證金管理與退還協(xié)議
- 二零二五年度河北省企業(yè)職工職業(yè)健康檢查合同
- 二零二五年度實體店鋪數(shù)字化轉(zhuǎn)型合作協(xié)議合同
- (二模)長春市2025屆高三質(zhì)量監(jiān)測(二)地理試卷(含答案)
- 2025天津市建筑安全員-C證考試題庫
- 2025年北京控股集團(tuán)招聘筆試參考題庫含答案
- TCVN22-越南建筑防火規(guī)范(中文版)
- 西方企業(yè)組織變革理論綜述
- 結(jié)構(gòu)力學(xué)中必須掌握的彎矩圖
- 國家二字碼大全--253個國家
- 公務(wù)接待制度公務(wù)接待審批單公務(wù)接待清單
- GB31644-2018食品安全國家標(biāo)準(zhǔn)復(fù)合調(diào)味料
- 大型儲罐壁板計算公式
- 華為結(jié)構(gòu)件FAI管理規(guī)范
評論
0/150
提交評論