Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Matlab

Mahmood H. Majeed
April 13, 2016

1 Flow Chart
• For start and end use • For conditional use:

• For input and output use

• For equation use: • For direction use:

Example 1. Make by flow-chart and program of the following equation


(
x2 + 5 if x 6= 0
y= 3
x + 5x − 2 if x = 0

Solution:
Flow-chart design: Program design
Start function y=name(x)
if x==0
y=x^3+5*x-2
input x else
y=x^2+5
end
No
x=0 y = x2 + 5 end

Yes
y = x3 + 5x − 2

print y print y

end

1
2 If Statements
IF statements use relational or logical operations to determine what steps to perform
in the solution of a problem. The relational operators in MATLAB R
for comparing
two matrices of equal size are shown in Table (1).

Table 1: Relational Operators

Relational Operator Meaning


< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
== Equal
∼= Not equal

There are several variations of the IF statement:

• Simple if statement

• Nested if statement

• If-else statement

• If-elseif-...-else statement
*****************************************************

• The general form of the simple if statement is:

if logical expression
statement
end

The logical expression has some symbol such as:

Table 2: Logical Operators

Logical Oper- Meaning


ator Symbol
& and
| or
∼ not

Example 2. Find y of the equation bellow where x=-1:

y = x2 + 2x − 5

Solution:
function y=name(x)
if x==-1
y=x^2+2*x+5
end

2
• The general form of a nested if statement is:

if logical expression 1
statement group 1
if logical expression 2
statement group 2
end
end

Example 3. If x > 5, then find y = −2x + 6, and find z = y 2 + 3x, where y ≤ 2.

Solution:
function z=name(x)
if x>5
y=2*x+6
if y<=2
z=y^2+3*x
end
end

• The general form of a if-else statement is:

if logical expression 1
statement group 1
else
statement group 2
end

Example 4. See Example 1:

• The general form of a if-elseif statement is:

if logical expression 1
statement group 1
elseif logical expression 2
statement group 2
elseif logical expression 3
statement group 3
..
.
else
statement group n
end

Example 5. Solve the quadratic equation.

ax2 + bx + c = 0

Solution:
function [x1,x2]=name(a,b,c)
D=b^2-4*a*c;
if D>0
x1=(-b+sqrt(D))/(2*a)

3
x2=(-b-sqrt(D))/(2*a)
elseif D=0
x1=-b/(2*a)
x2=x1
else
disp(’The root is complex’)
end

Example 6. Find y of the equation bellow, where x = 2 or x = 3:


πx
y = sin( ) + cos(πx)
2

Solution:
function [y]=name(x)
if x==2 | x==3
y=sin(pi*x/2)+cos(pi*x)
end

Example 7. Find y of the equation bellow, where −π < x ≤ π:


πx
y = sin( ) + cos(πx)
2

Solution: H.W.

You might also like