Fundamentals of Programming
The fundamentals of programming include: How to use abstraction to think in a general way about a collection of data and procedural steps How to describe the solution of a problem as an algorithm The three paradigms of computing and the position of MATLAB in that spectrum Th aspects of th apparently simple t k of Three t f the tl i l task f assigning a value to a variable
CHAPTER 2: Getting Started with MATLAB
ECE 102
ECE 102
1-2
MATLAB
MATLAB (MATrix LABoratory) is an interactive software system and programming language for many applications including numerical computations and graphics. Fundamental components of MATLAB: - A computing system that can execute sequences of instructions (one at a time). Instructions are in a text format and must follow a specified syntax and vocabulary (Ch. 3-9). - Library of modules for processing data (Ch. 10- 17) - Collections of toolboxes used in a number of engineering and scientific disciplines disciplines. - Graphical User Interface (GUI) that allows users to implement and interact with programs that solve specific problems.
Advantages - Excel at numerical calculations, especially matrix calculations - Large number of built-in MATLAB functions and toolboxes which can save a lot of time (with some computational speed penalties) - Built-in graphic capabilities that produce professional-looking graphs g p p p p gg p and images Disadvantages - It is an interpreted (i.e. not compiled) language, so it can be slow. - Does not work well for large computing projects.
ECE 102
ECE 102
Programming Language Background (sec 2.1)
Abstraction
expressing a quality apart from a particular implementation. To convert from degrees Celsius to Kelvin, y add 273 to g , you the temperature. He drove home from the office.
Programming Paradigms
Functional programming every programming operation is actually implemented as a function call with no side effects Procedural programming the basic programs or subprograms are sequences of operations on data items. Ex: MATLAB, C, Python Object-oriented programming (OOP) y p p g g characterized by the concept of packaging data items with the methods or functions that manipulate those data items. Ex: C++, Java
ECE 102
1-6
Algorithm
a sequence of instructions for solving a problem
Programming Paradigms g g g
Paradigm - a set of assumptions, concepts, values, and practices that constitutes a way of viewing reality for the community that shares them.
ECE 102
1-5
Summary Programming Languages
Abstraction lets you refer to collections of data or instructions as a whole. A algorithm i a set of instructions at an appropriate An l ith is t f i t ti t i t level of abstraction for solving a specific problem. A data class describes the type of data and the nature of operations that can be performed on that data. An object is a specific instance of a class with specific values that can be assigned to a variable variable.
Command History Workspace
MATLAB Desktop
Command Window
ECE 102
1-7
ECE 102
File menu
The Default Window
Cu e Current directory Command window
Summary MATLAB User Interface
The Command window lets you experiment with ideas by entering commands line-by-line and seeing immediate results. The Command History window lets you review and recall previous commands. The Workspace window lists the names, values, and class of your local variables. The Current Directory window lists the current files in the directory to which MATLAB is currently pointed. A Document window opens when a variable in the Workspace window is selected, to let you view and edit data items.
Workspace window
The Graphics window presents data and/or images when invoked by programs programs. The Editor window lets you view and modify text files. Scripts provide the basic mechanism for implementing solutions to problems.
Command history
ECE 102
1-9
ECE 102
1-10
MATLAB as a Calculator
The simplest way is to use MATLAB as a calculator. You can enter expressions at the command line of Command Window ( >> ) and evaluate them right away by pressing enter key at the end of expression.
Simple Example: Mary goes to the office supply store and buy 4 erasers at 25 cents each, 6 memo pads at 52 cents each, and 2 rolls of tape at 99 cents each, How many items did Mary buy and how much did they cost (in cents)?
>> 4 + 6 + 2 >> 1.5*3 + 5^2 ans = 29.5000 >> 2 * ans ans = 59
ECE 102
11
ans = 12 >> 4*25 + 6 * 52 + 2 * 99 ans = 610
ECE 102
12
Mathematical Operators (page A-1)
Mathematical expressions contain following algebraic operators.
Order of Precedence
When you are using operators in an expression, remember the rules of operator precedence:
Operation
Addition Additi Subtraction Multiplication Division
Algebra
3+4 34 3x4 3 4
MATLAB
3+4 34 3*4 3/4
Parentheses (round brackets): evaluated starting from ( )
the innermost pair.
2 3 4
Exponentiation: evaluated from left to right Multiplication and Division: evaluated from left to right Addition and Subtraction: evaluated from left to right Relational operators: evaluated from left to right
E Exponentiation ti ti
34
3^4
ECE 102
13
ECE 102
14
Precedence: example
Suppose you evaluate:
24 + 1 76
>> (2^4 + 1)/(7*6)
ans = 0.4048
Simple Example: Mary goes to the office supply store and buy 4 erasers at 25 cents each, 6 memo pads at 52 cents each, and 2 rolls of tape at 99 cents each, How many items did Mary buy and how much did they cost (in cents)?
To do this in MATLAB, you would enter
>> 4 + 6 + 2 ans = 12 >> 4*25 + 6 * 52 + 2 * 99 ans = 610
WRONG
15
What happens if you enter
>> 2^4 + 1/7*6
ans = 16.8571
ECE 102
ECE 102
16
Storing information in variables
>> eraser = 4 eraser = 4 >> pad = 6; >> tape = 2;
Example: Mary buys 4 erasers (25 each), 6 memo pads (52 each), and 2 rolls of tape (99 each), How many items did Mary buy and how much did they cost (in cents)?
Variables
For anything more complex than a simple one line calculation, it is useful to define variables.
Variable is a container for data
We can also think of variables as named locations in the computer memory in which a number can be stored.
semicolon is used to suppress the display
>> items = eraser + pad + tape items = 12 >>cost = eraser*25 + pad*52 + tape*99 cost = 610
ECE 102
17
ECE 102
18
Basic Data Manipulation (sec 2.2) Assigning Values to Variables
- Syntax similar to conventional algebra; different meaning.
Assignment operator ( = )
>> x = 3
% tell MATLAB to assign value 3 to variable x.
>> x = x + 2 % tell MATLAB to add 2 to the current value of x, and
% to replace the current value of x with this new value Variable on the left-hand side of the = operator is replaced by the value generated by the right-hand side. Only one variable can be on the left-hand side of the = operator >> 6 = x >> x + 2 = 20 0
z = x + y z = 4*x - y
WRONG !
The right-hand side of the = operator must have a computable value.
ECE 102
1-19
ECE 102
20
Memory as a Filing System
You can think of computer memory as a large set of boxes in which numbers can be stored. The values can be inspected and changed. Boxes can be labeled with a variable name.
Calculations with variables
Suppose we want to calculate the volume of a cylinder. Its radius and height are stored as variables in memory.
tell MATLAB to assign value 3 to variable A
>> volume = pi*radius^2*height
>> A=3 A= 3
3 A
ECE 102
21
volume
radius
height
ECE 102
>> volume = pi*radius^2*height
>> pi ans = 3.1416 >> radius = 2 radius = 2 >> height = 3.5 height = 3 5000 3.5000 >> volume = pi*radius^2*height volume = 43.9823
ECE 102
23
Rules for naming Variable
Variable names must begin with letters Variable names must contain less than 63 characters which can be letters, digits, and underscore character. MATLAB is case-sensitive: Speed, speed, SPEED, SpeeD, SPeeD are 5 different variables. Variable names must not be reserved word, i.e. special names which are part of MATLAB language. Punctuation characters are not allowed EXCEPT _ (underscore). Be careful not to confuse the number 1 with the letter l, or the number 0 with the letter o. Choose a variable name that indicate the quantity that it represents.
ECE 102
24
Predefined Constant (page A-4)
MATLAB has some special constants/variables:
Complex Numbers
MATLAB can handle complex numbers as easily as it can handle real numbers. The letters i and j are, be default, reserved to represent square root of 1.
pi represents the number = 3.14159... Inf represents infinity. NaN stands for Not-a-Number and occurs when an expression is
undefined
>> (3+2i) + (2-4i) ans = 5.0000 - 2.0000i
eps specifies an accuracy of a floating point precision smallest
possible difference between two floating-point numbers
i, j an imaginary unit of a complex number, -1 ans is a temporary variable containing the most recent answer.
ECE 102
25
ECE 102
26
MATLAB built-in functions (pages A-1 to A-8)
MATLAB has a large number of mathematical built-in functions, i.e. sqrt( ), mean( ), sum( ), An extensive list of MATLAB built-in functions is given in Appendix A.
Representation of Numbers
In science and engineering application, both very large and very small numbers are often used to describe physical quantities. MATLAB uses a scientific notation to represent such numbers.
>> 4.0 + sqrt(100) ans = 14
>> 5000000000 ans = 5.0000e+009 >> 0.00000001 ans = 1.0000e-008
= 1.0x10-8 = 5.0x109
ECE 102
27
ECE 102
28
Menus and the Toolbar
ECE 102
29
ECE 102
30
Commands for managing the work session (page A-3)
Command
clc clear clear var1 var2 quit who whos
MATLAB Help
Description
Clear the Command window Clear the workspace Remove the variables var1 and var2 from workspace Stop MATLAB List the variables currently in the workspace Lists the current variables and sizes, and indicate if they have imaginary parts Colon - generates an array having regularly spaced element Comma - separates elements of an array Semicolon - suppresses screen printing; also denotes a new row in an array Ellipsis; continues a line. ECE 102
31
: , ;
ECE 102
32
MATLAB Help - cont
Using MATLAB commands:
Example 3 (again)
Apply the computer-based Problem Solving method to the problem below: A fence around a field is shaped as shown below. It consists of a rectangle of length L and width W, and a right triangle that is symmetrical g g g ) about the central horizontal axis of the rectangle (isosceles right triangle). Suppose the width W (in meters (m)), and the enclosed area A (in square meters (m2)) are known (given). Write a computer program to find the total cost of building a fence. The materials and labor cost is $5 / m.
L D W
help function : describes what the function does, warns about any
unexpected results, and directs the user to other relates functions. >> help sqrt
lookfor function : allows the user to search functions based on a
keyword. >> lookfor sqrt
doc function: display the documentation for the MATLAB function.
>> doc sqrt
ECE 102
33
ECE 102
34
Ex 3: using Computer-based Problem Solving method
1. Specify the problem requirements: Finding the total cost for fencing the enclosed area given the cost is $5/m. 2. Analyze the problem - Input data - specify data to be used by the program Area (A) and Width (W) in meters - Output data - specify data to be generated by the program Total cost in dollars 3. Find the underlying equation(s) to be used in the program W2 = D2 + D2 = 2D2 => D2 = 0.5W2 => D = 0.7071W Area (A) = WL + 0.5D2 L = (A 0.5D2)/W
W L D
Example 3 (cont.)
4. Design an algorithm (step-by step approaches) to solve the problem. 1. Get input data (W and A) 2. Do the computations
find fi d D using W i (eqn i step 3) ( in ) find L using A, W, and D (eqn in step 3) find cost (eqn in step 3)
3. Display the result(s) - cost 5. Implement the algorithm convert each algorithm step into one or more statement(s) in a computer programming language used. 6. Test and verify the program by checking the results.
Cost = 5(W + 2L + 2D)
ECE 102
35
ECE 102
36
Example 2 An internal combustion engine
When combustion occurs, it pushes the piston down. This motion causes the connecting rod to turn the crank which causes the crankshaft to rotate. Develop a MATLAB program to compute and plot a distance d traveled by the piston as a function of the angle A, for given values of the length L1 and L2. typical values: L1 = 1 ft L2 = 0.5 ft 05 0 A 180o
Using trigonometry, we can write d = L1 cos B + L2 cos A Using the law of sines, sin A L1 sin B = sin B L2 = L2 sin A L1 B = sin-1 L2 sin A L1 (2) (1)
ECE 102
37
ECE 102
38
1. State the problem concisely:
- to compute d based on the angle A for given values of L1 and L2 using equations (1) and (2). - use enough values of A in the range of [0, 180] to generate a smooth plot.
2. 2 Specify the data to be used by the program. This is the input. program input
- L1 and L2 - angle A
4. Design an algorithm (step-by step approaches) to solve the problem. 1. Get/Enter input data (L1, L2 , A) 2. Do the computations (find d) d = L1 cos B + L2 cos A; - for each value of A, - find B B = sin-1 L2 sin A - from A and B, find d L1 3. Display the result (plot of d vs. A) 5. Implement the algorithm >> L1 = 1; >> L2 = 0.5; >> A_d = [0:0.5:180]; >> A_r = A_d * pi/180; >> B = asin((L2 / L1)*sin(A r)); L1) sin(A_r)); >> d = L1*cos(B) + L2*cos(A_r); >> plot(A_d, d); >> xlabel('A (degrees)'), ylabel('d (feet) '), grid
Specify the information to be generated by the program. This is the output.
- a plot of d versus A 3. Find the underlying equation(s) to be used in the program See previous slide.
ECE 102
39
ECE 102
40
6. Test and verify the program by checking the results. Pick a set of (simpler) input data and work through the solution steps by hand. Compare these results with what you got from the MATLAB program. Q: which values of A should we use? A = 0o , d = L 1 + L 2 A = 180o, d = L1 - L2 A = 90o, d = L1 2 - L2 2
d = L1 cos B + L2 cos A B = sin-1 L2 sin A L1 ECE 102
41
for L1 = 1 ft. and L2 = 0.5 ft, A (degree) d (ft.) 0 15 1.5 60 1.15 90 0.87 120 0.65 180 0.5 ECE 102
42
Script or M-file (page 35-41)
Two ways to perform operations in MATLAB: 1. Interactive mode, enter all commands directly at >> in Command Window. 2. Running a MATLAB program stored in a script file (M-file). (M file). - This script file contains sequence of MATLAB commands/instructions. Therefore, running (executing) it is equivalent to typing all commands one at a time into Command Window. - This script filename has extension .m, i.e. program1.m - This script file can be executed by - typing its filename at >> in Command Window - click on Menu bar of the .m file
Create a script file (M-file)
ECE 102
43
ECE 102
44
Comment Click on this to run the script file Write sequence of MATLAB commands that you want Save a script file with the name that you want in the desired directory (folder)
ECE 102
45
ECE 102
46
After running program1.m file
ECE 102
47