0% found this document useful (0 votes)
22 views

Chapter 1

1. MATLAB allows users to enter commands interactively or run scripts containing commands. 2. Script files contain MATLAB commands that are executed sequentially when the file is run. This is equivalent to typing the commands individually at the command prompt. 3. Comments can be added to any line in a script by including them after a % symbol. MATLAB will ignore everything after and including the % on each line.

Uploaded by

patrldainik2412
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Chapter 1

1. MATLAB allows users to enter commands interactively or run scripts containing commands. 2. Script files contain MATLAB commands that are executed sequentially when the file is run. This is equivalent to typing the commands individually at the command prompt. 3. Comments can be added to any line in a script by including them after a % symbol. MATLAB will ignore everything after and including the % on each line.

Uploaded by

patrldainik2412
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Chapter 01

An Overview of MATLAB

1
The Default MATLAB Desktop

Source: MATLAB 2
Entering Commands and Expressions
MATLAB retains your previous keystrokes.

Use the up-arrow key to scroll back through the


commands.

Press the key once to see the previous entry, and so on.

Use the down-arrow key to scroll forward. Edit a line using


the left- and right-arrow keys the Backspace key, and the
Delete key.

Press the Enter key to execute the command.

3
Scalar Arithmetic Operations

Symbol Operation MATLAB form


 exponentiation: a b a b
* multiplication: ab a*b
a
/ right division: a /b = a/b
b
b
\ left division: a \ b = a\b
a
+ addition: a + b a+b
− subtraction: a − b a− b

4
An Example Session
>> 8/10
ans =
0.8000
>> 5*ans
ans =
4
>> r=8/10
r =
0.8000
>> r
r =
0.8000
>> s=20*r
s =
16

5
Order of Precedence

Precedence Operation
First Parentheses, evaluated starting with the
innermost pair.

Second Exponentiation, evaluated from left to right.


Third Multiplication and division with equal
precedence, evaluated from left to right.

Fourth Addition and subtraction with equal


precedence, evaluated from left to right.

6
Examples of Precedence 1

>> 8 + 3*5
ans =
23
>> 8 + (3*5)
ans =
23
>>(8 + 3)*5
ans =
55

7
Examples of Precedence 2

>> 3*4^2 + 5
ans =
53
>>(3*4)^2 + 5
ans =
149
>>27^(1/3) + 32^(0.2)
ans =
5
>>27^(1/3) + 32^0.2
ans =
5
>>27^1/3 + 32^0.2
ans =
11

8
Commands for Managing the Work
Session 1

clc Clears the Command window.


clear Removes all variables from memory.
clear x y Removes the variables x and y from
memory.

exist(‘abc’) Determines if a file or variable exists


having the name ‘abc’.

quit Stops MATLAB.

9
Commands for Managing the Work
Session 2

who Lists the variables currently in memory.


whos Lists the current variables and sizes and
indicate if they have imaginary parts.
colon

Colon; generates an array having regularly


spaced elements.
comma

Comma; separates elements of an array.


semicol on

Semicolon; suppresses screen printing;


also denotes a new row in an array.
ellipsi s

Ellipsis; continues a line.


10
Special Variables and Constants

ans Temporary variable containing the most


recent answer.

eps Specifies the accuracy of floating point


precision.

i, j The imaginary unit the square root of negative 1

Inf Infinity.
NaN Indicates an undefined numerical result.
pi The number π.

11
Complex Number Operations
The number c1 = 1 − 2i is entered as follows: c1 = 1-2i.
An asterisk is not needed between i or j and a number, although
it is required with a variable, such as c2 = 5i*c1.
Be careful. The expressions
y = 7/2*i
and
x = 7/2i
give two different results:
y = (7/2)i = 3.5i
and
x = 7/(2i) = −3.5i.

12
Numeric Display Formats 1

format short Four decimal digits (the default);


13.6745.

format long 16 digits; 17.27484029463547.

format short e Five digits (four decimals) plus


exponent; 6.3792e+03.

format long e 16 digits (15 decimals) plus exponent;


6.379243784781294e−04.

13
Numeric Display Formats 2

format bank Two decimal digits; 126.73.

format + Positive, negative, or zero; +.

format rat Rational approximation; 43/7.

format compact Suppresses some blank lines.

format loose Resets to less compact display mode.

14
The Toolstrip after Selecting the HOME
Tab.

Source: MATLAB 15
Arrays
The numbers 0, 0.1, 0.2, ..., 10 can be assigned to the variable u by
typing u = 0:0.1:10.
To compute w = 5 sin(u) for u = 0, 0.1, 0.2, ... , 10, the session is;
>>u = 0:0.1:10;
>>w = 5*sin(u);
The single line, w = 5*sin(u), computed the formula w = 5
sin(u) 101 times.

16
Array Index
>>u(7)
ans =
0.6000
>>w(7)
ans =
2.8232
Use the length function to determine how many values are in
an array.
>>m = length(w)
m =
101

17
Polynomial Roots
To find the roots of x3 − 7 x 2 + 40x – 34 = 0, the session is
>>a = [1,-7,40,-34];
>>roots(a)
ans =
3.0000 + 5.000i
3.0000 - 5.000i
1.0000

The roots are x = 1 and x = 3 ± 5i.

18
Some Commonly used Mathematical
Functions
Function MATLAB syntax1
ex exp(x)
x sqrt(x)

ln x log(x)
log10 x log10(x)
cos x cos(x)
sin x sin(x)
tan x tan(x)
cos −1 x acos(x)
sin −1 x asin(x)
tan −1 x atan(x)
1TheMATLAB trigonometric functions use radian
measure.

19
Some MATLAB Plotting Commands
Command Description
[x,y] = ginput(n) Enables the mouse to get n points from a plot,
and returns the x and y coordinates in the vectors
x and y.

grid Puts grid lines on the plot.


gtext(‘text’) Enables placement of text with the mouse.
plot(x,y) Generates a plot of the array y versus the array x
on rectilinear axes.

xlabel(‘text’) Adds a text label to the horizontal axis (the


abscissa).

ylabel(‘text’) Adds a text label to the vertical axis (the


ordinate).

20
A Figure Window Showing a Plot.

Access the text alternative for slide images.

Source: MATLAB 21
When you type problem1
1. MATLAB first checks to see if problem1 is a variable and
if so, displays its value.
2. If not, MATLAB then checks to see if problem1 is one of
its own commands, and executes it if it is.
3. If not, MATLAB then looks in the current directory for a
file named problem1.m and executes problem1 if it
finds it.
4. If not, MATLAB then searches the directories in its
search path, in order, for problem1.m and then
executes it if found.

22
System, Directory, and File Commands

cd dirname Changes the current directory to dirname.

dir Lists all files in the current directory.

dir dirname Lists all the files in the directory dirname.

path Displays the MATLAB search path.

pwd Displays the current directory.

which item Displays the path name of item if item is a


function or file. Identifies item as a variable if so.

23
You can perform operations in MATLAB
in two ways
1. In the interactive mode, in which all commands are entered
directly in the Command window, or
2. By running a MATLAB program stored in script file. This
type of file contains MATLAB commands, so running it is
equivalent to typing all the commands—one at a time—at
the Command window prompt. You can run the file by
typing its name at the Command window prompt.

24
Inserting Comments
The comment symbol may be put anywhere in the line.
MATLAB ignores everything to the right of the % symbol.
For example,
>>% This is a comment.
>>x = 2+3 % So is this.
x =
5
Note that the portion of the line before the % sign is
executed to compute x.

25
The MATLAB Command Window with the
Editor Open.

Source: MATLAB 26
Keep in mind when using script files
1. The name of a script file must begin with a letter, and may
include digits and the underscore character, and can much
longer than you will ever need.
2. Do not give a script file the same name as a variable.
3. Do not give a script file the same name as a MATLAB
command or function. You can check to see if a command,
function or file name already exists by using the exist
command.

27
Debugging Script Files
Program errors usually fall into one of the following
categories.
1. Syntax errors such as omitting a parenthesis or comma, or
spelling a command name incorrectly. MATLAB usually
detects the more obvious errors and displays a message
describing the error and its location.
2. Errors due to an incorrect mathematical procedure, called
runtime errors. Their occurrence often depends on the
particular input data. A common example is division by
zero.

28
To locate program errors
Try the following:
1. Test your program with a simple version of the problem
which can be checked by hand.
2. Display any intermediate calculations by removing
semicolons at the end of statements.
3. Use the debugging features of the Editor/Debugger.

29
Programming Style 1

1. Comments section
• The name of the program and any key words in the
first line.
• The date created, and the creators’ names in the
second line.
• The definitions of the variable names for every input
and output variable. Include definitions of variables
used in the calculations and units of measurement for
all input and all output variables!
• The name of every user-defined function called by the
program.

30
Programming Style 2

2. Input section Include input data and/or the input


functions and comments for documentation.
3. Calculation section
4. Output section This section might contain
functions for displaying the output on the screen.

31
Some Input/Output Commands

disp(A) Displays the contents, but not the


name, of the array A.

disp(‘abc’) Displays the text string enclosed


within single quotes.

x = input(‘abc’) Displays the text in quotes, waits for


user input from the keyboard, and
stores the value in x.

x = input(‘abc’, ‘s’) Displays the text in quotes, waits for


user input from the keyboard, and
stores the input as a string in x.

32
Example of a Script File 1

Problem:
• The speed v of a falling object dropped with no initial
velocity is given as a function of time t by v = gt.
• Plot v as a function of t for 0 < t < tf inal, where tf inal is the
final time entered by the user.

33
Example of a Script File 2

% Program falling_speed.m:
% Plots speed of a falling object.
% Created on May 5, 2017 by W. Palm
%
% Input Variable:
% tfinal = final time (in seconds)
%
% Output Variables:
% t = array of times at which speed is
% computed (in seconds)
% v = array of speeds (meters/second)
%

34
Example of a Script File 3

% Parameter Value:
g = 9.81; % Acceleration in SI units
%
% Input section:
tfinal = input(’Enter final time in seconds:’);
%

35
Example of a Script File 4

% Calculation section:
dt = tfinal/500;
% Create an array of 501 time values.
t = 0:dt:tfinal;
% Compute speed values.
v = g*t;
%
% Output section:
plot(t,v),xlabel(‘t (s)’),ylabel(‘v m/s)’)

36
Getting Help From the Textbook
Throughout each chapter margin notes identify where key
terms are introduced.
Each chapter contains tables summarizing the MATLAB
commands introduced in that chapter.
At the end of each chapter is a summary guide to the
commands covered in that chapter.
Appendix A contains tables of MATLAB commands, grouped
by category, with the appropriate page references.
There are four indexes. The first lists MATLAB commands
and symbols, the second lists Simulink blocks, the third lists
commands for the Symbolic Math toolbox, and the fourth lists
topics.
37
Getting Help From MATLAB: The Function
Browser after plot has been selected

Access the text alternative for slide images.

Source: MATLAB 38
MATLAB Help Functions
help func_name: Displays in the Command window a
description of the specified function func_name.
lookfor topic: Displays in the Command window a
brief description for all functions whose description includes
the specified key word topic.
doc func_name: Opens the Help Browser to the
reference page for the specified function func_name,
providing a description, additional remarks, and examples.

39
Steps in engineering problem solving 1

1. Understand the purpose of the problem.


2. Collect the known information. Realize that some of it
might later found to be unnecessary.
3. Determine what information you must find.
4. Simplify the problem only enough to obtain the required
information. State any assumptions you make.
5. Draw a sketch and label any necessary variables.
6. Determine which fundamental principles are applicable.

40
Steps in engineering problem solving 2

7. Think generally about your proposed solution approach


and consider other approaches before proceeding with
the details.
8. Label each step in the solution process.
9. If you solve the problem with a program, hand check the
results using a simple version of the problem. Checking
the dimensions and units and printing the results of
intermediate steps in the calculation sequence can
uncover mistakes.

41

You might also like