Computer Programming: Starting With MATLAB

Transcription

Computer Programming:Starting with MATLABAsst. Prof. Dr. Yalçın İşlerIzmir Katip Celebi University

Outline Matlab EnvironmentWorking in the Command WindowUsing MATLAB as a CalculatorDisplay FormatsElementary FunctionsVariablesScript FilesExamples

MATLAB MATrix LABoratoryWidely used in universities and collegesPowerful environment for technical computingNo need having prior experience inprogramming Based on Numerical analysis Symbolic calculations

Starting MATLAB

Choosing Desktop Layout

Changing Current Folder

MATLAB EnvironmentCurrent DirectoryCommand WindowWorkspaceCommandHistory

Figure Windowt 0:pi/50:10*pi;plot3(sin(t),cos(t),t);

Editor Window

Working with Command WindowWrite a command and thepress Enter keyAnswer will be shown (ansmeans answer)Write a command withending by a semicolon andthe press Enter keyAnswer will NOT be showndue to the semicolon means that Matlab isready for a new command

Running Command After running a command (writing thecommand, and pressing the Enter-key), youcannot change it. To correct the command,you should give a new correct command A previous command can be seen, by pressingUp-Arrow key. Before pressing Enter key, youcan move the cursor by using Left- and RightArrow keys, and then you can make changes.

Some Notes If a semicolon (;) is typed at the end of acommand, the answer will not be shown, butthe command will be executed, of course. No matter which command is written after thepercent symbol (%), it will not be executed,which is called commenting. clc: Clear the command window

Arithmetic nAddition 3 21()Subtraction-3-22 Multiplication*3*23*/\Division (rightdivision)/3/24 -Left division\3\2Exponentiation 3 2x \ y equals to y / x for scalars.if precedences are equal, theleft-side operation will beexecuted first.

Display formatsTry 290 / 7 afterCommandDescriptionThe example outputformat shortFixed-point with 4-decimal digits between0.001 and 1000, otherwise «long e» format.41.4286format longFixed-point with 14-decimal digits between0.001 and 1000, otherwise «long e» format.41.42857142857143format short eScientific notation with 4 decimal digits4.1429e 001format long eScientific notation with 15 decimal digits4.142857142857143e 001format short gBest of 5-digit fixed or floating points41.429format long gBest of 15-digit fixed or floating points41.4285714285714format bankTwo decimal points41.43format compact Eliminates empty linesformat looseAdds empty lines (opposite of compact)

Elementary FunctionsFunctionDescriptionExamplesqrt(x)Square rootsqrt(81)nthroot(x,n)Real n-th root of a real number xnthroot(80,5)exp(x)𝑒𝑥exp(5)abs(x)Absolute valueabs(-24)log(x)Natural logarithm (base e ln)log(1000)log10(x)Base 10 logarithmlog10(1000)factorial(x)𝑥!factorial(5)

Trigonometric FunctionsFunctionDescriptionsin(x) sind(x) asin(x) asind(x)Sine and inverse sinecos(x) cosd(x) acos(x) acosd(x)Cosine and inverse cosinetan(x) tand(x) atan(x) atand(x)Tangent and inverse tangentcot(x) cotd(x) acot(x) acotd(x)Cotangent and inverse cotangentpiπHyperbolic trigonometric functions are also present.

Rounding FunctionsFunctionDescriptionExampleround(x)Rounds to the nearest integerround(17/5) 3fix(x)Rounds towards zerofix(13/5) 2ceil(x)Rounds towards infinityceil(11/5) 3floor(x)Rounds towards minus infinityfloor(-9/4) -3rem(x, y)Returns the remainder after x isdivided by yrem(17,5) 2sign(x)Signum function, returns 1 if x 0, -1if x 0, and 0 if x 0sign(17) 1

Variables A variable, is a name made of a letter or acombination of several small and/or capital letters,digits, and underscore character ( ), contains anumerical value. A variable name must begin with a letter (Turkishcharacters and spaces are NOT allowed) Case-sensitive: AA, Aa, aA, and aa are all different. Avoid using the names of built-in function. If youprefer giving a function name to a variable, youcan use the variable but the function. Forbidden to use keywords: break, case, catch,continue, else, elseif, end, for, function, global, if,otherwise, persistent, return, switch, try, while

Assignment Operator

Predefined Variables ans: A variable that has the value of the lastexpression that was not assigned to a specificvariable. pi: The number of π. eps: The smallest difference between twonumbers that Matlab can recognize. inf: Used fo infinity. i: Defined as 1 (to show imaginary part ofcomplex numbers) j: Same as i. NaN: Not a Number (for example, 0/0).

Script Files A script file is a sequence of MATLAB commands, alsocalled a program during all remaining lecture sessionsof this course. When a script file runs (is executed), MATLAB executesthe commands in the order as if they are typed in theCommand Window. Using a script file is convenient because it can be editedand executed many times even after turn off and turnon the computer. Script files can be typed and edited in any text editor(preferably Matlab Editor). Script files are also called M-files because the extension.m is used when they are saved.

Creating and Saving a Script FileSave the program

Running a Script FileRun the program

Running an Already-Saved ScriptRun the programby typing its name

Laboratory SessionDo sample applications in Chapter 1 of thetextbook.

Homework #3Not later than the next week:Solve problems 3, 4, 7, 12, 13, 16, 19, 20, 25, and 26from the Chapter 1 of the textbook using Matlab.

When a script file runs (is executed), MATLAB executes the commands in the order as if they are typed in the Command Window. Using a script file is convenient because it can be edited and executed many times even after turn off and turn on the computer. Script files can be typed and edited in any text editor (preferably Matlab Editor).