matlabnoteschap04
matlabnoteschap04
Topics Covered:
• Programming Overview
• Relational Operators and Logical Variables
• Logical Operators and Functions
• Conditional Statements
• For Loops
• While Loops
• Debugging MATLAB programs
Programming Overview:
MATLAB programming can be used to solve very computationally
intensive problems which may require thousands or hundreds of
thousands of calculations. Operations can be:
• Sequential: Calculations are executed in order from the top down.
• Conditional: Calculations are made based on the answer (either true or
false) to a question.
• Iterative: Calculations are made over and over until a condition is met.
Sequential Conditional (If-Then) Iterative (For Loops) Iterative (While Loops)
Statement
Group 1
Statement
Group 2
Statement
Group 3
Relational Operators and Logical Variables:
Relational Operators make comparisons between numbers or arrays.
The result of a comparison is either:
• = 0 (if the comparison is false) or
• = 1 (if the comparison is true)
The result can be used as a variable. When used to compare arrays, the
relational operators compare the arrays on an element-by-element basis.
The arrays must have the same dimension. When comparing an array to a
scalar, all of the elements of the array are compared to the scalar.
Problem 4.4:
Suppose that x = 6. Find the
results of the following
operations by hand and use
MATLAB to check your results.
Problem 4.6:
Suppose that 𝑥 = 10, −2, 6, 5, −3 and 𝑦 = 9, −3, 2, 5, −1 . Find
the results of the following operations by hand and use MATLAB to
check your results.
Problem 4.8:
𝑦>0
Compute 𝑧
If-Else Statements:
If-Else Statements provide
two options based on the result
of the Logical Expression.
Create the following MATLAB
program. Once you’ve checked
that it is working correctly,
change the value of x to 50.
If-Elseif-Else Statements:
This is the General Form
of the if statement. Create
the following MATLAB
program. Once you’ve
checked that it is working
correctly, change the
value of x to 5 and then to
7.
Problem 4.16:
Write a script file using Conditional If-Elseif-Else statements to
evaluate the following function, assuming that 𝑥 = −2, 0, and 6. The
function is:
𝑒 𝑥+1 for 𝑥 < −1
𝑦 = 2 + cos 𝜋𝑥 for − 1 ≤ 𝑥 ≤ 5
10 𝑥 − 5 + 1 for 𝑥 > 5
For Loop:
The For Loop is a structure that
repeats a set of commands or
calculations a specified number of
times. Create the following
MATLAB program. In this case,
the variable x is a scalar.
For Loop:
The For Loop can be used to
Load a Vector with values. The
Counter k is used to Index
through the vector elements.
• What happens if you don’t
Initialize x? [Comment out x(1)
= 3 and rerun]
• How many elements does x
have?
• What change would you make if
you wanted x to have only 3
elements?
Debugging Tool:
Click on the Horizontal Lines to
the right of the line numbers. This
creates Breakpoints on the lines
of code.