[法语学习]MIT麻省理工matlab.doc

上传人:音乐台 文档编号:1986158 上传时间:2019-01-28 格式:DOC 页数:62 大小:28.64KB
返回 下载 相关 举报
[法语学习]MIT麻省理工matlab.doc_第1页
第1页 / 共62页
[法语学习]MIT麻省理工matlab.doc_第2页
第2页 / 共62页
[法语学习]MIT麻省理工matlab.doc_第3页
第3页 / 共62页
亲,该文档总共62页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

《[法语学习]MIT麻省理工matlab.doc》由会员分享,可在线阅读,更多相关《[法语学习]MIT麻省理工matlab.doc(62页珍藏版)》请在三一文库上搜索。

1、6.094Introduction to Programming in MATLABDanilo .epanovi.IAP 2010Lecture 1: Variables, Scripts, and OperationsCourse Layout.Lectures.1: Variables, Scripts and Operations.2: Visualization and Programming.3: Solving Equations, Fitting.4: Images, Animations, Advanced Methods.5: Optional: Symbolic Math

2、, SimulinkCourse Layout.Problem Sets / Office Hours.One per day, should take about 3 hours to do.Submit doc or pdf (include code, figures).No set office hours but available by email.Requirements for passing.Attend all lectures.Complete all problem sets (-, , +).Prerequisites.Basic familiarity with p

3、rogramming.Basic linear algebra, differential equations, and probabilityOutline(1)Getting Started(2)Scripts(3)Making Variables(4)Manipulating Variables(5)Basic PlottingGetting Started.To get MATLAB Student Version for yourself.https:/msca.mit.edu/cgi-bin/matlab.Use VPN client to enable off-campus ac

4、cess.Note: MIT certificates are required.Open up MATLAB for Windows.Through the START Menu.On Athena.add matlab.matlab &Command WindowCurrent directoryWorkspaceCommand HistoryMaking Folders.Use folders to keep your programs organized.To make a new folder, click the Browsebutton next to Current Direc

5、tory.Click the Make New Folderbutton, and change the name of the folder. Do NOT use spaces in folder names. In the MATLAB folder, make two new folders: IAPMATLABday1.Highlight the folder you just made and click OK.The current directory is now the folder you just created.To see programs outside the c

6、urrent directory, they should be inthe Path. Use File- Set Path to add folders to the pathCustomization.File .Preferences.Allows you personalize your MATLAB experienceCourtesy of The MathWorks, Inc. Used with permission.MATLAB Basics.MATLAB can be thought of as a super-powerful graphing calculator.R

7、emember the TI-83 from calculus? .With many more buttons (built-in functions).In addition it is a programming language.MATLAB is an interpreted language, like Java.Commands executed line by lineHelp/Docs.help.The mostimportant function for learning MATLAB on your own.To get info on how to use a func

8、tion:.help sin.Help lists related functions at the bottom and links to the doc.To get a nicer version of help with examples and easy-to-read descriptions:.doc sin.To search for a function by specifying keywords:.doc + Search tabOutline(1)Getting Started(2)Scripts(3)Making Variables(4)Manipulating Va

9、riables(5)Basic PlottingScripts: Overview.Scripts are .collection of commands executed in sequence.written in the MATLAB editor.saved as MATLAB files (.m extension).To create an MATLAB file from command-line.edit helloWorld.m.or clickCourtesy of The MathWorks, Inc. Used with permission.Scripts: the

10、Editor* Means that its not savedLine numbersCommentsMATLAB file pathHelp filePossible breakpointsDebugging toolsReal-time error checkCourtesy of The MathWorks, Inc. Used with permission.Scripts: Some Notes.COMMENT!.Anything following a %is seen as a comment.The first contiguous comment becomes the s

11、cripts help file.Comment thoroughly to avoid wasting time later.Note that scripts are somewhat static, since there is no input and no explicit output.All variables created and modified in a script exist in the workspace even after it has stopped runningExercise: ScriptsMake a helloWorldscript.When r

12、un, the script should display the following text: .Hint: use dispto display strings. Strings are written between single quotes, like This is a stringHello World!I am going to learn MATLAB!Exercise: ScriptsMake a helloWorldscript.When run, the script should display the following text: .Hint: use disp

13、to display strings. Strings are written between single quotes, like This is a string.Open the editor and save a script as helloWorld.m. This is an easy script, containing two lines of code:.% helloWorld.m.% my first hello world program in MATLAB.disp(Hello World!);.disp(I am going to learn MATLAB!);

14、Hello World!I am going to learn MATLAB!Outline(1)Getting Started(2)Scripts(3)Making Variables(4)Manipulating Variables(5)Basic PlottingVariable Types.MATLAB is a weakly typed language.No need to initialize variables!.MATLAB supports various types, the most often used are.3.84.64-bit double (default)

15、.a.16-bit char.Most variables youll deal with will be vectors or matrices of doubles or chars.Other types are also supported: complex, symbolic, 16-bit and 8 bit integers, etc. You will be exposed to all these types through the homeworkNaming variables.To create a variable, simply assign a value to

16、a name:.var1=3.14.myString=hello world.Variable names.first character must be a LETTER.after that, any combination of letters, numbers and _.CASE SENSITIVE! (var1is different from Var1) .Built-in variables. Dont use these names!.iand jcan be used to indicate complex numbers.pihas the value 3.1415926

17、.ansstores the last unassigned value (like on a calculator).Infand -Infare positive and negative infinity .NaN represents Not a NumberScalars.A variable can be given a value explicitly.a = 10.shows up in workspace!.Or as a function of explicit values and existing variables .c = 1.3*45-2*a.To suppres

18、s output, end the line with a semicolon.cooldude = 13/3;Arrays.Like other programming languages, arrays are an important part of MATLAB.Two types of arrays(1)matrix of numbers (either double or complex)(2)cell array of objects (more advanced data structure)MATLAB makes vectors easy!Thats its power!R

19、ow Vectors.Row vector: comma or space separated values between brackets.row = 1 2 5.4 -6.6.row = 1, 2, 5.4, -6.6; .Command window:.Workspace:Courtesy of The MathWorks, Inc. Used with permission.Column Vectors.Column vector: semicolon separated values between brackets .column = 4;2;7;4.Command window

20、:.Workspace:Courtesy of The MathWorks, Inc. Used with permission.size & length.You can tell the difference between a row and a column vector by:.Looking in the workspace.Displaying the variable in the command window.Using the size function.To get a vectors length, use the length functionMatrices.Mak

21、e matrices like vectors.Element by element.a= 1 2;3 4;.By concatenating vectors or matrices (dimension matters).a = 1 2;.b = 3 4;.c = 5;6;.d = a;b;.e = d c;.f = e e;a b a;.str = Hello, I am John;.Strings are character vectors1234a.=.save/clear/load.Use saveto save variables to a file.save myFile a b

22、.saves variables a and b to the file myfile.mat.myfile.mat file is saved in the current directory.Default working directory is .MATLAB.Make sure youre in the desired folder when saving files. Right now, we should be in:.MATLABIAPMATLABday1.Use clearto remove variables from environment.clear a b.look

23、 at workspace, the variables a and b are gone.Use loadto load variable bindings into the environment.load myFile.look at workspace, the variables a and b are back.Can do the same for entire environment.save myenv; clear all; load myenv;Exercise: VariablesGet and save the current date and time.Create

24、 a variable startusing the function clock.What is the size of start? Is it a row or column?.What does startcontain? See help clock.Convert the vector startto a string. Use the function datestr and name the new variable startString.Save startand startStringinto a mat file named startTimeExercise: Var

25、iablesGet and save the current date and time.Create a variable startusing the function clock.What is the size of start? Is it a row or column?.What does startcontain? See help clock.Convert the vector startto a string. Use the function datestr and name the new variable startString.Save startand star

26、tStringinto a mat file named startTime.help clock.start=clock;.size(start).help datestr.startString=datestr(start);.save startTime start startStringExercise: VariablesRead in and display the current date and time.In helloWorld.m, read in the variables you just saved using load.Display the following

27、text:.Hint: use the dispcommand again, and remember that strings are just vectors of characters so you can join two strings by making a row vector with the two strings as sub-vectors.I started learning MATLAB on *start date and time*Exercise: VariablesRead in and display the current date and time.In

28、 helloWorld.m, read in the variables you just saved using load.Display the following text:.Hint: use the dispcommand again, and remember that strings are just vectors of characters so you can join two strings by making a row vector with the two strings as sub-vectors.load startTime.disp(I started le

29、arning MATLAB on . startString);I started learning MATLAB on *start date and time*Outline(1)Getting Started(2)Scripts(3)Making Variables(4)Manipulating Variables(5)Basic PlottingBasic Scalar Operations.Arithmetic operations (+,-,*,/).7/45.(1+i)*(2+i).1 / 0.0 / 0.Exponentiation ().42.(3+4*j)2.Complic

30、ated expressions, use parentheses.(2+3)*3)0.1.Multiplication is NOT implicit given parentheses.3(1+0.7) gives an error.To clear command window.clcBuilt-in Functions.MATLAB has an enormouslibrary of built-in functions.Call using parentheses passing parameter to function.sqrt(2).log(2), log10(0.23).co

31、s(1.2), atan(-.8).exp(2+4*i).round(1.4), floor(3.3), ceil(4.23).angle(i); abs(1+i);Exercise: ScalarsYou will learn MATLAB at an exponential rate! Add the following to your helloWorld script:.Your learning time constant is 1.5 days. Calculate the number of secondsin 1.5 days and name this variable ta

32、u.This class lasts 5 days. Calculate the number of seconds in 5 days and name this variable endOfClass.This equation describes your knowledge as a function of time t:.How well will you know MATLAB at endOfClass? Name this variable knowledgeAtEnd. (use exp).Using the value of knowledgeAtEnd, display

33、the phrase: .Hint:to convert a number to a string, use num2str/1tke.=.At the end of 6.094, I will know X% of MATLABExercise: Scalars.secPerDay=60*60*24;.tau=1.5*secPerDay;.endOfClass=5*secPerDay.knowledgeAtEnd=1-exp(-endOfClass/tau);.disp(At the end of 6.094, I will know . num2str(knowledgeAtEnd*100

34、) % of MATLAB)Transpose.The transpose operators turns a column vector into a row vector and vice versa.a = 1 2 3 4+i.transpose(a).a .a.Thegives the Hermitian-transpose, i.e. transposes and conjugates all complex numbers.For vectors of real numbers .and give same resultAddition and Subtraction.Additi

35、on and subtraction are element-wise; sizes must match (unless one is a scalar):.The following would give an error.c = row + column.Use the transpose to make sizes compatible.c = row+ column.c = row + column.Can sum up or multiply elements of vector.s=sum(row);.p=prod(row);123321121130321414221 .+.=1

36、23911210132303333.=.Element-Wise Functions.All the functions that work on scalars also work on vectors.t = 1 2 3;.f = exp(t);.is the same as.f = exp(1) exp(2) exp(3);.If in doubt, check a functions help file to see if it handles vectors elementwise.Operators (* / ) have two modes of operation.elemen

37、t-wise.standardOperators: element-wise.To do element-wise operations, use the dot: .(.*, ./, .). BOTH dimensions must match (unless one is scalar)!.a=1 2 3;b=4;2;1;.a.*b, a./b, a.b .all errors.a.*b, a./b, a.(b) .all valid412321144224313313131.*ERROR.*.*.=.=.=111123123222123246333123369333333.*.*.=.=

38、2222121223434.Can be any dimension.=.Operators: standard.Multiplication can be done in a standard way or element-wise.Standard multiplication (*) is either a dot-product or an outer-product.Remember from linear algebra: inner dimensions must MATCH!.Standard exponentiation () can only be done on squa

39、re matrices or scalars.Left and right division (/ ) is same as multiplying by inverse.Our recommendation: just multiply by inverse (more on this later)41232111133111*.=.=1111233692221236121833312391827333333*.=.=1212122343434*Must be square to do powers.=.Exercise: Vector OperationsCalculate how man

40、y seconds elapsed since the start of class.In helloWorld.m, make variables called secPerMin, secPerHour, secPerDay, secPerMonth(assume 30.5 days per month), and secPerYear(12 months in year), which have the number of seconds in each time period.Assemble a row vector called secondConversionthat has e

41、lements in this order: secPerYear, secPerMonth, secPerDay, secPerHour, secPerMinute, 1.Make a currentTimevector by using clock.Compute elapsedTimeby subtracting currentTimefrom start.Compute t(the elapsed time in seconds) by taking the dot product of secondConversionand elapsedTime(transpose one of

42、them to get the dimensions right)Exercise: Vector Operations.secPerMin=60;.secPerHour=60*secPerMin;.secPerDay=24*secPerHour;.secPerMonth=30.5*secPerDay;.secPerYear=12*secPerMonth;.secondConversion=secPerYear secPerMonth . secPerDay secPerHour secPerMin 1;.currentTime=clock;.elapsedTime=currentTime-s

43、tart;.t=secondConversion*elapsedTime;Exercise: Vector OperationsDisplay the current state of your knowledge.Calculate currentKnowledgeusing the same relationship as before, and the t we just calculated:.Display the following text:/1tke.=.At this time, I know X% of MATLABExercise: Vector OperationsDi

44、splay the current state of your knowledge.Calculate currentKnowledgeusing the same relationship as before, and the t we just calculated:.Display the following text:.currentKnowledge=1-exp(-t/tau);.disp(At this time, I know . num2str(currentKnowledge*100) % of MATLAB);/1tke.=.At this time, I know X% of MATLABAutomatic Initialization.Initiali

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1