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

Chapter 4_Programming With Matlab

Uploaded by

Thanh Phúc Hồ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Chapter 4_Programming With Matlab

Uploaded by

Thanh Phúc Hồ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Introduction to Computer for Engineers

Programming with Matlab


➢Program Design and Development
➢Relational Operators and Logical Variables
➢Logical Operators and Functions
➢Conditional Statements
➢Loops
➢The switch Structure
➢Debugging Matlab Programs
➢Applications to Simulation
An algorithm:

➢ an ordered sequence of precisely defined


instructions that performs some task in a finite
amount of time.

➢must have ability to alter the order of its instructions


using a control structure.

Algorithm operations: sequential operations,


conditional operations, iterative operations (loops)
Sequential operations: executed in order.

Conditional operations: first ask a question to be


answered with a true/false answer and the select the
next instruction based on the answer.

Iterative operations (loops): repeat the execution of


a block of instructions
Structured programming:

➢a technique for designing programs using hierarchy


of modules, each having a single entry and single exit
point.

➢control is passed downward through the structure


without unconditional branches to higher levels of the
structure.

Modules in Matlab can be built-in or user-defined


functions
The advantages of structured programming:
➢Structured programs are easier to write because the programmer
can study the overall problem first and then deal with the details
later.

➢ Modules (functions) written for one application can be used for


other applications (this is called reusable code).

➢Structured programs are easier to debug because each module is


designed to perform just one task and thus it can be tested
separately from the other modules.

➢ Structured programming is effective in a teamwork environment


because several people can work on a common program, each
person developing one or more modules.

➢Structured programs are easier to understand and modify,


especially if meaningful names are chosen for the modules and if the
documentation clearly identifies the module’s task.
Top-down design:

➢ a method for creating structured programs

➢ describe a program’s intended purpose at a very


high level initially
Process of top-down design:

1. State the problem concisely.


2. Specify the data to be used by the program. This is “input”.
3. Specify the information to be generated by the program. This is
“output”.
4. Work through the solution steps by hand or with a calculator; use
a simple set of data if necessary.
5. Write and run the program.
6. Check the output of the program with your hand solution.
7. Run the program with your input data and perform a reality check
on the output.
8. If you will use the program as a general tool in the future, test it
by running it for a range of reasonable data values; perform a
reality check on the results.
Program documentation:
is aided by structured charts and flow charts.

Structured charts:
➢ a graphical description showing how the different parts of
the program are connected together.
➢is useful in the initial stages of top-down design.
➢displays the organization of a program without showing the
details of the calculations and decision process.
➢show the connection between the main program and the
modules.
➢Is limited by their size.
Structure chart of a game program

Main Program

Game Status Strategy


Player input
Display Program
Program
Program

Player input Program: allows the human player to input a move.


Game Status Display Program: updates and displays the game grid.
Strategy Program: contains the computer’s strategy for selecting its movies.
Flowcharts:
➢ is used in the programs containing the conditional
statements.
➢displays the various paths (called “branches”) that a
program can take.
➢use diamond symbol to indicate decision points.
➢Is limited by their size.
Flowchart representation of the if statement
Start

False
Logical
Expression

True

Statements

End
Pseudocode:
➢ used to avoid dealing immediately with the possibly
complicated syntax of the programming language.
➢uses natural language and mathematical expressions to
construct statements that look like computer statements but
without detailed syntax.
➢use some simple Matlab syntax to explain the operation of
the program.
➢is an imitation of the actual computer code.
➢useful for outlining a program before writing the detailed
code.
Sequential Operations
Compute the perimeter p and the area A of a triangle whose
sides are a, b, c. The formulas are:

A = s(s − a )(s − b )(s − c )


p
p = a+b+c s=
2

1. Enter the side lengths a, b, and c.


2. Compute the perimeter p.
(p=a+b+c)
3. Compute the semiperimeter s.
(s=p/2)
4. Compute the area A.
5. Display the results p and A. A = s(s − a )(s − b)(s − b)
6. Stop
The program is:

a=input('Enter the value of side a: ');


b=input('Enter the value of side b: ');
c=input('Enter the value of side c: ');
p=a+b+c;
s=p/2;
A=sqrt(s*(s-a)*(s-b)*(s-c));
disp('The perimeter is: ')
p
disp('The area is: ')
A
Conditional Operations
Given the (x,y) coordinates of a point, compute its polar
coordinates (r,), where
−1  y 
r= x +y
2 2
 = tan  
x
1. Enter the coordinates a and b.
2. Compute the hypoteneuse r. r = x + y
2 2

3. Compute the angle 


3.1. If x0:  = tan −1  y 
x
 y
Else:  = tan   + pi
−1
3.2. x
4. Convert the angle to degrees. =  *180 / pi
5. Display the results r and .
6. Stop
Iterative Operations
Determine how many terms are required for the sum of the
series 10k2 - 4k +2, k=1, 2, 3, … to exceed 20,000. What is
the sum for this many terms.
Because we do not know how many times we must evaluate
the expression 10k2 - 4k +2, we use a “while” loop.
1. Initialize the total to zero.
2. Initialize the counter to zero.
3. While the total is less than 20,000 compute the total.
3.1. Increment the counter by 1: k=k+1;
3.2. Update the total: total = 10 * k 2
− 4 * k + 2 + total
4. Display the current value of the counter.
5. Display the value of the total.
6. Stop.
Finding Bugs

Debugging program is the process of finding and removing


the “bugs” or errors, in a program. Such errors include:
➢Syntax errors (omitting a parenthesis, comma, spelling a
command name incorrectly).  Matlab displays the errors
and its location.
➢Errors due to an incorrect mathematical procedure
(runtime errors). They do not occur every time, depend on
the particular input data. (Ex: division by zero).
Relational operators are used to compare arrays.

Relational operator Meaning


< Less than
<= Less than or equal
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
>> x=[2 3 6]; >> z=(x>y)
>> y=[5 3 8];
>> z=(x<y) z=

z= 0 0 0

1 0 1 >> z=(x>=y)

>> z=(x<=y) z=

z= 0 1 0

1 1 1 >> z=(x==y)

z=

0 1 0

>> z=(x~=y)

z=

1 0 1
Logical operators

Operator Name Definition


~ NOT ~A returns an array the same dimension as A; the new
array has ones where A is zero and zeros where A is
nonzero.
& AND A & B returns an array the same dimension as A and B;
the new array has ones where both A and B have
nonzero elements and zeros where either A or B is zero.
A|B returns an array the same dimension as A and B; the
| OR new array has ones where at least one element in A or B
is nonzero and zeros where A and B are both zero.
Operator for scalar logical expressions. A&&B returns
&& Short-Circuit AND true if both A and B evaluate to true, and false if they do
not.
|| Short-Circuit OR Operator for scalar logical expressions. A| |B returns true
if either A or B or both evaluate to true, and false if they
do not.
Order of precedence for operator types

Precedence Operator type


First Parentheses; evaluated starting with the innermost pair.
Second Arithmetic operators and logical NOT (~); evaluated from left
to right.
Third Relational operators; evaluated from left to right.
Fourth Logical AND.
Fifth Logical OR.
Example

x=[1 3 5] ; y=[0 -2 5] z=0&3 x=[6,3,9] ; y=[14,2,9] ;


1. z=~x z=2&3 a=[4,3,12]
2. u1=~x>y z=0&0 1. z=(x>y)&a
3. u2=(~x)>y z=[5,-3,0,0] & [2,4,0,5] 2. z=(x>y)&(x>a)
4. u3=~(x>y) z=1&2+3 3. z=x>y&x>a
5. u4=(x<=y) z=1&(2+3)
z=5<6&1 z=[5,-3,0,0]|[2,4,0,5]
z=3<5|4==7
z=(5<6)&1
z=1|0&1
z=1|0&0
z=0&0|1
z=~3==7|4==6
find function
find(x) computes an array containing the indices (not values)
of the nonzero elements of the array x.
Ex:
x=[5,-3,0,0,8] ; y=[2,4,0,5,7]
>>z=find(x&y)
>>values=y(x&y)
>>how_many=length(values)
The if statement

if logical expression if logical expression 1


statements if logical expression 2
end statements
end
Ex: y = x end
Can be replaced by
if x>=0
y=sqrt(x) if logical expression 1&2
end statements
end
x,y
Example

z=0; w=0; x>=


False
0?
if (x>=0) & (y>=0)
z= sqrt(x)+sqrt(y) True

w=log(x)-3*log(y) False
y>=0
?
end
The values of z and w are computed True

only if both x and y are nonnegative.


Compute z,w
Otherwise, z and w retain their
values of zero.

End

Flow chart corresponding to the pseudocode example


The else statement Start

if logical expression 1 Logical


False
statement group 1 expressio
n

else
statement group 2 True
end
Statement Statement
group 1 group 2

End

Flow chart of the else structure


Example
Supposing that y = x for x>=0 Start
and y=ex -1 for x<0
x>=0
False
if x>=0 ?

y=sqrt(x)
else
y=exp(x)-1 True
end
y=sqrt(x) y=exp(x)-1

End

Flow chart
Use if with array.
True if all of elements
Consider the following statements of x <0

x = [ 4 -9 16]
if x<0
disp (‘Some of elements of x are negative.’)
else
y = sqrt (x)
end

When this program is run, it gives the result

y=2 0+3.000i 4
Use if with array.
True if all of elements
Consider the following statements of x >=0

x = [ 4 -9 16]
if x>=0
y = sqrt (x)
else
disp (‘Some of elements of x are negative.’)
end

When this program is run, it gives the result

Some of elements of x are negative.


The elseif statement if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
else
statement group 3
end
else and elseif can be omitted if not required.
If both are used, else statement must come after elseif statement
to take care of all conditions that might be unaccounted for.
elseif does not require a separate end statement.
Start

Logical
False
expressio
n1

True

Statement Logical
False
group 1 expressio
n2

True

Statement Statement
group 2 group 3

End Flow chart of the general if structure


Example
ln x if x5
Supposing that y=
 x if 0 x5

if x>=5 if x>=5
y=log(x) y=log(x)
else elseif x>=0
if x>=0 y=sqrt(x)
y=sqrt(x) end
end
end
Example  ln x if x  10

Supposing that y =  x if 0  x  10
e x − 1 if x0

if x>10
y=log(x)
elseif x>=0
y=sqrt(x)
else
y=exp(x) - 1
end
Practice
1. Given the first order equation: ax+b=0.
Write the program to find its root.
Supposing that a and b are optional inputs.
2. Given the second order equation: ax2+bx+c=0.
Write the program to find its roots.
Supposing that a, b and c are optional inputs.

You might also like