Computer Programming In MATLAB

Transcription

IntroductionComputer Programming inMATLABProf. Dr. İrfan KAYMAZAtatürk UniversityEngineering FacultyDepartment of Mechanical EngineeringAtatürk University

What is a computer?IntroductionComputer is a device that computes, especially a programmable electronic machinethat performs high-speed mathematical or logical operations or that assembles,stores, correlates, or otherwise processes information.Computer Program is a set of ordered instructions that enable a computer to carryout a specific task.Writing a computer program1- Algorithm: step-by-step procedure for calculations2- Choosing language: right language for program3- EncodingLanguages: Scientific and engineering: MATLAB, Pascal, C, C , Java Database: DBASE,SQL,FOXPRO,PARADOX Operating system: C ,C , Java General purpose: C ,C ,Java ,VB and PascalAtatürk University

What is algorithm?Introduction An algorithm is an effective method expressed as a finite list of welldefined instructions for calculating a function. A set of instructions or procedures for solving a problem.Atatürk University

Example 1IntroductionLet’s write an algorithm to calculate the sum of two numbersStep 1 : StartStep 2 :enter X valueStep 3 :enter Y valueStep 4 :Z X YStep 5 :print Z valueStep 6 :EndAtatürk University

Example 2IntroductionWrite an algorithm to calculate the mean of two numbers given.Step 1: startStep 2 :enter X valueStep 3 :enter Y valueStep 4 :Z X YStep 5 :mean Z/2Step 6 :print meanStep 7 :endAtatürk University

Example 3IntroductionAn algorithm to calculate the area of a rectangle with given length.If the length of edge is defined as negative, it will be redefined.Let’s define Variables:First edge length of rectangle: a, Second edge length of rectangle : b,Area of rectangle: areaAlgorithm:S1 : startS2 : enter a valueS3 : if a 0 repeat the second stepS4 : enter b valueS5 : if b 0, repeat the fourth stepS6 : area a*bS7 : print area valueS8 : endAtatürk University

FlowchartsIntroductionFlow chart gives the logical flow of the solution in a diagramatic form.Atatürk University

FlowchartsIntroductionAtatürk University

Example 4IntroductionDraw a flowchart to find the sum of numbers from 1 to 100Algorithm:S1 : StartS2 : enter sum as zeroS3 : enter counter as zeroS4 : add counter to sumS5 : add 1 to counterS6 : if counter 100 then go to S4S7 : print sumS8 : EndAtatürk University

IntroductionExample 5Draw a flowchart to find the root of the following first order equation,Ax B 0StartA 0EndAtatürk University

Example 6IntroductionDraw a flowchart to find the mean and sum ofsquares, square roots, cubes, squares of cubes ofthe numbers from 1 to 100Atatürk University

Example 7IntroductionValues of F(x) function depending onthe x are as follows. X changes from 0to 10 with the steps of 0.5. Draw theflowchart to calculate F(x) for each xvalues0 X 2 f(x) X2 X 3 f(x) X -X3 -223 X 4 f(x) X2 -2X 134 Xf(x) X4 -3X2 -43Atatürk University

Example 8IntroductionDraw a flowchat to find the largest of three numbers of A, B, and C.Atatürk University

Example 9IntroductionDraw a flowchat for computing factorial N (N!)Atatürk University

What is MATLABIntroductionMATLAB is the acronym for MATrix LABoratory.MATLAB, “the language of technical computing,” is a programming environmentfor algorithm development, data analysis, visualization, and numeric computation.MATLAB; has a user-friendly interface, has many of scientific and mathematical function, provides a wide variety of techniques to display data graphically.Atatürk University

What is MATLAB?IntroductionTOOLBOXESMATLAB has a rich family of application-specific solution packages calledtoolboxes, which are comprehensive collections of MATLAB functions related toparticular problems. Optimization Toolbox Control System Toolbox Neural Network Toolbox Fuzzy Logic Toolbox Atatürk University

ReferencesIntroductionSome useful p://www.owlnet.rice.edu/ dx.edu/ on.ucl.ac.uk/courses/spsci/matlab/Atatürk University

Start MATLABIntroductionStarting Matlab:double click the Matlab iconCommand window and Matlab prompt (prompt is a symbol on the commandwindow indicating that the matlab is waiting for an input. )The MATLAB Help Window gives you access to a great deal of useful informationabout the MATLAB language and MATLAB computing environment. It also has anumber of example programs and tutorials.Quiting Matlab Type quit at the prompt, or Select Exit Matlab from the File menuAtatürk University

MATLAB - View folders and m-filesWorkspace- View program variables- Double click on a variableto see it in the Array EditorWorkspace- View program variables- Double click on a variabto see it in the Array Ed- View folders and m-filesCommandWindowCommandWindow- Type commandsType commands-- Commandwindow iswhere user interacts- Commandwindowwith MATLABiswhere user interactswith MATLABCommandHistoryCommandHistory- View past commands- View past commandsAtatürk University

Matlab as a calculatorIntroduction- Type expressions at the , and press return- Result is computed, and displayed as ans- Use numbers, , -, *, /, sin, cos, exp, abs 2 5 3 2 sin(pi/4) 2*(2 3)Atatürk University

Matlab as a calculatorIntroductionUse ( ) symbols as parentheses, {} and [] mean something different.ExampleAtatürk University

Matlab as a calculatorIntroduction Previously entered commands can be recalled by dragging them from thecommand history to the command window or by pressing the up-arrow key,and then it can be edited. If a statement is terminated with a semicolon ( ; ), no results will be displayed.Otherwise results will appear before the next prompt. If you omit the semicolon at the end of a line, that causes the assigned valueto be printed on the screen. To clear command window, type clc and press enter.Atatürk University

Variables in MATLABIntroduction Variables are named locations in memory where numbers, strings and otherelements of data may be stored while the program is working. Variable names are used to assign the result of an expression to a variable. Variables do not need to be declared before assignment.A single “equal” sign ( ) is the assignment operator,LHS (left hand side) RHS (right hand side)Write the expression on the RHS, and assign the result to the variable named onthe LHS (The left-hand-side needs to be a single variable name).Atatürk University

Rules for variable namesIntroduction Variable names are combinations of letters and numbers, but must start with alatter. All of the characters in variable names can not be the numbers. Variable names do not contain punctuation except underscore. Space between any characters in variable names can not be used. You can useunderscore if you want a space. Matlab functions must not be used as variable names. Be sure to write the exact name of variable when you recall it. Because matlabis case sensitive for variable names. It distinguishes between uppercase andlowercase letters. So A and a are not the same variable. You should not use a MATLAB Function names (sin, cos, length, sqrt etc.). cos 5changes cos function to a variable name.Atatürk University

IntroductionVariable namesLegal XABAAC 5;sqrt(13);exp(2);2*BA 1tan(pi/4)Illegal (all for different reasons) D sqrt(E) 1; 3 E 3*A 14 F 2 3Atatürk University

Aritmetic operatorsIntroductionMATLAB utilizes the following arithmetic operators: */ 'additionsubtractionmultiplicationdivisionpower operatortransposeWe will use dot ‘.’ in front of these operators to make themelement by element operatorsAtatürk University

IntroductionMatlab functionsCommonly used Matlab functionsFunctionSymbolExampleSine,sin( )sinsin(pi)FunctionCosine,cos( )coscos(pi)Eksponential,tantan(pi)Arcsine,arcsin( )asinasin(0)Arccosine,arccos( )acosacos(0)arctangent,arctan( )atanatan(1)Tangent,tan( )SymbolExampleexpexp(2)Natural logarithm,ln(x)loglog(10)Common (base 10)logarithmlog10log10(10)exSquare root, xsqrtsqrt(25)Absolute value, x absabs(3)Atatürk University

Expressions suitable for MatlabIntroductionAtatürk University

Mathematical troductionFloating-point relative accuracyImaginary unitInfinityLargest value of specified integer typeSmallest value of specified integer typeImaginary unitNot-a-NumberRatio of circle's circumference to its diameterLargest positive floating-point numberSmallest positive normalized floating-point numberAtatürk University

Keyboard symbols tilde! exclamation mark% per cent wedge& ampersand or and* asterisk( left parenthesis) right parenthesisunderscore- hyphen, minus or dash equals plus{ left brace (curly parenthesis)} right brace (curly parenthesis)[ left bracket] right bracket vertical barIntroduction\ backslash/ slash? question mark: colon; semi-colon" quote, quotation mark' apostrophe, single quote less greater, comma. dot* star plusAtatürk University

IntroductionHomeworkPlease write the following nice mathematical expression suitablefor computer programminga x 3cb a1 c2 a b4b 5 cd 34a (ac) 3 2a aAtatürk University

Next lectureIntroductionM-Files andControl statements Atatürk University

Computer Programming in MATLAB Atatürk University Engineering Faculty Department of Mechanical Engineering . Atatürk University Introduction Computer is a device that computes, especially a programmable electronic machine that performs high-sp