# MATLAB & Its Applications In Engineering 李清都 副教授

## Presentation on theme: "MATLAB & Its Applications In Engineering 李清都 副教授"— Presentation transcript:

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 1: Introduction Contents Covered:  Why MATLAB?  Simple demos.  How to learn MATLAB? Objectives:  Establish the basic concepts of MATLAB  Understand the advantage and disadvantage of MATLAB

Why MATLAB ？ There are totally 87 students I may arrange 10 times of assignments Each time I will randomly look through 20 students’ work Question: What is the probability that you will never be selected? How high is the risk not to do the assignments?

Why MATLAB ？ 1-[(87-20)/87] 10 = ? Want to know the result ?!  Calculate by hand  use a calculator  use C language I have much more important things to do than to calculate this boring figure…

Why MATLAB ？ Using C language: main() { float m; m = 1-((107-20)/107)^10; printf( “ %f ”,m); }

Why MATLAB ？ Using C language: main() { float m; m = 1-((107-20)/107)^10; printf( “ %f ”,m); } If only there was just line 3…

You need such a powerful tool  Powerful compute ability  Easy of use MATL AB

MATLAB ： the most popular computer program optimized to perform engineering and scientific calculations.

What can MATLAB do? Mathematical computing Visual results System modeling Graphic user interface

The advantages of MATLAB Easy of use Platform independence Predefined functions Device-Independent Plotting Graphic user interface MATLAB compiler

The disadvantages of MATLAB Slower execute speed –Matlab is interpreted language other than compiled language –All the variables use the highest precision Higher cost

The MATLAB Environment Command window Work Space Command history

How to learn MATLAB? The most important is to program more and practice more The best teacher is Matlab help, not me, nor any person else Think more your idea  search in help  find a function  programming Good programming practice

Assignment: Install Matlab and run the demo Any question or suggestion, please email to: liqd@cqupt.edu.cn with title: matlab - your name - your question

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 2: Variables & Arrays Contents Covered: basic conceptions of MATLAB variables and arrays initialize/save/load MATLAB variables and arrays Objectives:  Firmly grasp the naming rules of MATLAB variables.  Fully grasp the initialize and addressing method of a array.  Memorize the basic special variables, such as pi, i, j, ans, NaN.  Grasp how to save and load MATLAB variables

Arrays Vectors: 1 dimension Matrix: 2 or more dimensions A scalar is an array with only one row and one column. All data, even scalars, are arrays.

Variables Naming Rule must begin with a letter, followed by any combinations of letters, numbers, and the underscore character. C can begin with ‘_’ !!! Only the first 31 characters are significant. A MATLAB variable is a region of memory containing an array, which is known by a user-specified name.

Special Variables i, j, pi, NaN, ans, eps MATLAB has some predefined variables and users should avoid using them create new variables.

Good Programming Practice Must using meaningful names Include a data dictionary in the header of the program Use lowercase letters to name a variable Use underscore as separator if the name is long

Initialize the Array There are 3 common ways: Using assignment statement Read from a file From keyboard

Initializing Variables in Assignment Statement Using assignment statement Var = expression Initializing with shortcut expression Var = first : incr : last Initializing with build-in functions Var = zeros(?) Var = ones(?)

Initializing Variables from file MATLAB formatted file load xxx.mat save file_name var1, var2, var3… ASCII file load file_name.xxx -ascii

Initializing Variables with Keyboard Input var = input(‘Enter an input value:’)

Multi-dimensional Arrays Create a multi-dimensional array e.g. c is a 2x3x2 array c(:, :, 1) = [1 2 3; 4 5 6]; c(:, :, 2) = [7 8 9; 0 1 2]; MATLAB always allocates array elements in column major order. a(1, 1, 1) -> a(2, 1, 1) -> a(1, 2, 1) -> a(2, 2, 1) -> a(1, 3, 1)… a(10) = 1

Subarray Select and use subsets of a array c = [1 2 3; 4 5 6]; a = c(1, [ 2 3]) b = c([1 2], [ 2 3]) The end function c(1, 2:end) Assignment to subarray c(1, [ 2 3]) = [12 13] Assigning a scalar to a subarray c(2, [ 2 3]) = 99

Assignment: Excises 2.1, 2.2, 2.3 2.4

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 3: Operations Contents Covered: basic conceptions of scalar/array/matrix operations the main differences between array & matrix operation operation rules Objectives:  Firmly grasp the differences between array and matrix operation.  Fully grasp the hierarchy & the rules of the operations  Memorize some basic MATLAB functions, such as sqrt, …  Start to write M-file and debug it

MATLAB Operations Scalar operation Array operation Matrix operation the differences between array operation & matrix operation!!!

Scalar operation Examples: A = 4*2 A = 2^((8+2)/5) A = [ 1 2 3 4]; b = A^2;

Array operation Examples: A = [ 1 2 3 4]; B = [ 5 6 7 8]; C = A.* B; If as array operation, the result is [ 5 12 21 32] Array operations are operations performed between arrays on an element-by-element basis.

Matrix operation Examples: A = [ 1 2 3 4]; B = [ 5 6 7 8]; C = A * B; If as matrix operation, the result is [ 19 22 43 50] Matrix operations follow the normal rules of linear algebra such as matrix.

Array & Matrix operators OperationArray operatorMatrix operator Addition++ Sub.-- Multiplex..** Right Div..// Left Div..\\ Exponentiation.^^ Usually array operators have one extra ‘.’ than matrix operators.

Hierarchy of Operations Rules: 1.The contents of all parentheses 2.Exponentials 3.Multiplication and division 4.Additions and subtractions Question: What is the execute sequences of the following assignment? a = sin(pi^2/2*3+1) + 4*(2-1)

Build-in MATLAB functions min, max sqrt, mod sin, cos, tan, atan, asin, acos abs, angle exp, log ceil, round, floor, fix These are very common MATLAB functions which we will use quite frequently.

M-File File  new  M-file And then write your code Debug… Think…

Assignment: Excises 2.6, 2.7, 2.8, 2.9

MATLAB & Its Applications In Engineering

Lect. 4: Display & Plotting Contents Covered: MATLAB data format three functions: disp, fprintf, plot the elements of a MATLAB figure Objectives:  Understand the concepts of MATLAB data format  Firmly grasp the usage of ‘disp’, ‘fprintf’, ‘plot’  Strengthen the skill on writing and debugging M-file

Data Formats format Set display format for output Syntax 1.format format by itself, changes the output format to the default appropriate for the class of the variable currently being used. For floating-point variables, for example, the default is format short (i.e., 5-digit scaled, fixed-point values).

Data Formats 2.format type format type changes the format to the specified type. The tables shown below list the allowable values for type. 3. format('type') format('type') is the function form of the syntax.

Data Formats Short Long Short e Short g Long e Long g Bank Hex Rat Compact Loose + format options format command only controls the display format. It will not change the precision of the data.

Data Formats TypeResult shortScaled fixed point format, with 4 digits after the decimal point. For example, 3.1416. longScaled fixed point format with 14 or 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.141592653589793. long eFloating point format, with 14 or 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.141592653589793e+000. short gBest of fixed or floating point, with 4 digits after the decimal point. For example, 3.1416. long gBest of fixed or floating point, with 14 to 15 digits after the decimal point for double; and 7 digits after the decimal point for single. For example, 3.14159265358979.

Data Formats Value for typeResult +The symbols +, - and blank are printed for positive, negative and zero elements. Imaginary parts are ignored bankFixed dollars and cents. For example, 3.14 hexHexadecimal (hexadecimal representation of a binary double- precision number). For example, 400921fb54442d18 ratRatio of small integers. For example, 355/113

Data Formats Value for typeResult Example compact Suppresses excess line feeds to show more output in a single screen. Contrast with loose. theta = pi/2 theta = 1.5708 looseAdds linefeeds to make output more readable. Contrast with compact. theta = pi/2 theta = 1.5708

Data Formats Examples 1.>> format long >> pi ans =3.141592653589793 2. format + >> -2 ans = -

Data Formats Note The format function affects only how numbers are displayed, not how MATLAB computes or saves them.

disp disp( x) disp(X) displays an array, without printing the array name. If X contains a text string, the string is displayed. Another way to display an array on the screen is to type its name, but this prints a leading "X=," which is not always desirable.

disp Note that disp does not display empty arrays. Examples 1.str = [ ‘the value of pi = ‘ ， num2str(pi) ] ； disp(str) The result: the value of pi = 3.1416

disp 2. >> x = [1 2 3]; >> disp(['The values of x are: ', num2str(x)]); The values of x are: 1 2 3 (The num2str function converts numbers to their string representations. This function is useful for labeling and titling plots with numeric values.)

fprintf fprintf( format, data) fprintf( format, data) formats data and displays the results on the screen. Examples 1. This command fprintf('Hello'); The result: >>Hello

fprintf 2.fprintf(‘the value of pi is %f \n’, pi); The result: >> fprintf('the value of pi is %f',pi) >>the value of pi is 3.141593

Programming pitfalls Note ‘fprintf’ will only display the real part of a complex number!!! example: a = 3+4i; fprintf(‘fprintf: a = %f’, a);

Summary There are 3 ways to display a data: 1)Leave the semicolon off the end of the statement 2)Use ‘disp’ function 3)Use ‘fprintf’ function It is better to use ‘disp’ to display a complex number.

Plotting It is really not so difficult as you imaged. How great if I can create a beautiful graph with MATLAB!

What’s the first ? Right! You need a piece of paper. figure(number)

plot Plot(x,y,’s’) x axis and y axis linetype y 黄色. 点 - 连线 m 洋红 o 圈 : 短虚线 c 蓝绿色 x x- 符号 -. 长短线 r 红色 + 加号 -- 长虚线

plot  title figure name  xlabel/ylabel axis  legend graphic symbol  grid on off grid

Then you can plot! x = 1:100; y = sin(x*pi/10); plot(x,y)

Then you can plot! x = 1:100; y = sin(x*pi/10); plot(x,y,’--r’,’linewidth’,5)

Plot more… x = 1:100 y = sin(x*pi/10) z = 0.5*cos(x*pi/20) plot(x,y,x,z)

Add more control title('my first plot') xlabel('x') ylabel('y') grid on axis([0 110 -2 2]) legend('sin(x*pi/10)', '0.5*cos(x*pi/20)');

plot3 3-D line plot Syntax plot3(X1,Y1,Z1,...) plot3(X1,Y1,Z1,LineSpec,...) plot3(...,'PropertyName',PropertyValue,...) h = plot3(...)

plot3 Examples Plot a three-dimensional helix. t = 0:pi/50:10*pi; plot3(sin(t),cos(t),t) grid on axis square

plot3

subplot Create axes in tiled positions Examples To plot income in the top half of a figure and outgo in the bottom half,

subplot income = [3.2 4.1 5.0 5.6]; outgo = [2.5 4.0 3.35 4.9]; subplot(2,1,1); plot(income) title('Income') subplot(2,1,2); plot(outgo) title('Outgo')

subplot

Logarithmic scales Purpose Semilog scale plot of frd object Syntax semilogx(...) same as plot semilogy(...) same as plot

Logarithmic scales Description semilogx(...) is the same as plot(...), except a logarithmic (base 10) scale is used for the x-axis. semilogy(...) is the same as plot(...), except a logarithmic (base 10) scale is used for the y-axis.

Logarithmic scales x = 1:100 y = x.^3 semilogy(x,y)

Logarithmic scales semilogx(x,y)

Logarithmic scales loglog(x,y)

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 5: Branch Statement Contents Covered: Top-down design Techniques relational & logical operators Branch statements: ‘if-elseif-else-end’, ‘switch-case-otherwise-end’ Objectives:  Understand the concepts of Top-down design flow  firmly grasp the usage of relational & logical operators  Firmly grasp the usage of ‘if-elseif-else-end’, ‘switch case otherwise end’  Strengthen the skill on writing and debugging M-file

Top-down Design Flow

More complicated control statements To solve complicated problems, you have to write more complicated programs. branching & looping

Relational operators == ~= > < >= <= 1) not to confuse the ‘==‘ with ‘=‘ 2) relational operators has lower hierarchy than arithmetic operations

Good Programming practice Always use parentheses to indicate the order 7+3 < 2+11 (7+3) < (2+11)

What is the result? a = 0; b = sin(pi); c = (a == b);

Logical operators & | xor ~

Hierarchy of operations 1)Arithmetic operators 2)Relational operators (from left to right) 3)~ 4)& 5)| 6)!

Logical functions isequal( ) isempty ( ) isinf ( ) isnan ( ) isnumeric ( )

The if construct if expression_1 statement_1 elseif expression_2 statement_2 else statement_3 end

The switch construct switch ( swtich_expression) case case_expr_1 statement_1 case case_expr_2 statement_2 otherwise statement_3 end

Assignment: Excises 3.2, 3.3, 3.4, 3.5

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 5: Branch Statement Contents Covered: Top-down design Techniques relational & logical operators Branch statements: ‘if-elseif-else-end’, ‘switch-case-otherwise-end’ Objectives:  Understand the concepts of Top-down design flow  firmly grasp the usage of relational & logical operators  Firmly grasp the usage of ‘if-elseif-else-end’, ‘switch case otherwise end’  Strengthen the skill on writing and debugging M-file

Top-down Design Flow

More complicated control statements To solve complicated problems, you have to write more complicated programs. branching & looping

Arithmetic operators + - * /

Relational operators == ~= > < >= <= 1) not to confuse the ‘==‘ with ‘=‘ 2) relational operators has lower hierarchy than arithmetic operations

Logical operators & | xor ~

Hierarchy of operations 1)Arithmetic operators 2)Relational operators (from left to right) 3)~ 4)& 5)|

Good Programming practice Always use parentheses to indicate the order 7+3 < 2+11 >> 7+3<2+11 ans = 1

Good Programming practice (7+3) < (2+11) >> (7+3)<(2+11) ans =1 0>1&2 2>1&2 >> 0>1&2 >> 2>1&2 ans =0 ans =1

Good Programming practice 2+7>12<2&1 >> 2+7>12<2&1 ans =1 2&1>2+7>12 >> 2&1>2+7>12 ans =0

What is the result? a = 0; b = sin(pi); c = (a == b);

Logical functions isequal( ) isempty ( ) isinf ( ) isnan ( ) isnumeric ( )

Logical functions isequal( ) Examples

Logical functions isempty ( ) Examples

Logical functions isinf ( ) Examples

Logical functions isnan ( ) Examples

Logical functions isnumeric ( ) Examples

The if construct if expression_1 statement_1 elseif expression_2 statement_2 else statement_3 end

The switch construct switch ( swtich_expression) case case_expr_1 statement_1 case case_expr_2 statement_2 otherwise statement_3 end

Example using switch construct

Assignment: Excises 3.2, 3.3, 3.4, 3.5

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 6: Loops Contents Covered: Loop statements: ‘while-end’, ‘for-end’ Objectives:  Understand the concepts of loops  Firmly grasp the usage of ‘while-end’, ‘for-end’  Strengthen the skill on writing and debugging M-file

Loops Loops are MATLAB constructs that permit us to execute a sequence of statements more than once.

The while construct while Repeatedly execute statements while condition is true

The while construct Syntax while expression … … code_block end

Example using while construct Example ATTENTION

Example using while construct The result

Example using while construct Calculate the average (arithmetic mean) and the standard deviation of a set of input positive numbers.

How to program? 1.State the problem 2.Define the inputs/outputs 3.Design the algorithm think more…!!!

The algorithm 1.input the numbers 2.Calculate the value until a negative number is input a) a variable sum_x is needed to store the summary of the inputs b) a variable sum_x2 is needed to store the summary of the square value of the inputs 3. Print the results

The for construct For Execute block of code specified number of times

The for construct Syntax for index = expr … … code_block end

Example using for construct Example

Example using for construct Example

Difference between while and for

Break & Continue Break Terminate execution of for or while loop Continue Pass control to next iteration of for or while loop

Break & Continue s1 = 0; for ii=1:10 if (ii >5) & (ii<8) break; else s1 = s1 + ii; end

Break & Continue s2 = 0; for ii=1:10 if (ii >5) & (ii<8) continue; else s2 = s2 + ii; end

Debug Break debug break.avi Continue continue.avi

Assignment: Excises 4.1, 4.3, 4.4

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 7: Functions Contents Covered: the concepts of function the construct of MATLAB functions how to write/call MATLAB functions the difference between MATLAB functions and C functions Objectives:  Understand the concepts/construct of function  Understand the difference between MATLAB function and C function  Grasp the skill of writing and debugging MATLAB function

When program gets bigger and bigger… It is not good to write all the code in one block or one file. It is better each subtask can be described (or solved) in a separate function.

The structure of a complicated program

The benefits Independent Testing of subtasks Reusable code Isolation from unintended side effects

The construct of MATLAB function function [ outarg1 outarg2 …] = functioname(inarg1, inarg2, …) % H1 comment line % Other comment line … (executable code) … (return) Diff. from C

return If the function file is inserted return, when performing to the statement, process turns to call this function position

A simple function function distance = dist2(x1, y1, x2, y2) % function DIST2 calculate the distance of … %... distance = sqrt( (x1-x2).^2 + (y1 – y2).^2); return;

How to call a function d = dist2(0, 0, 3, 4);

Function with multiple outputs function [r, theta] = rect2polar(x, y) % RECT2POLAR convert rectangular to polar coordinates %... r = sqrt( x.^2 + y.^2); theta = 180/pi * atan2(y, x); there are multiple outputs,you must use”[ ]”

A simple function

The result

User-Defined Functions Command file/function file+function file

User-Defined Functions

Function file+subfile

User-Defined Functions Inline +command/function file

Function calling Calculate the value of ‘s’ for a given ‘n’. s = 1! + 2! + 3! + … n!

How to solve? 1.Write a function to get the factorial value of x ( factorial_1(x) = x! ) 2.Write the code to sum up all the factorial values from factorial_1(1) to factorial_1(n)

Think more… 1.How to reduce the operations? 2.Is there a build-in MATLAB function to calculate the factorial value ? 3.How to find a MATLAB build-in function if you never used before?

Assignment: Excises 5.9, 5.23

MATLAB & Its Applications In Engineering 李清都 副教授 liqd@cqupt.edu.cn

Lect. 8: MATLAB Modeling Contents Covered: How to model an engineering problem with MATLAB? Objectives:  Grasp the skill of using MATLAB to model and solve a problem  Grasp the skill of writing and debugging MATLAB problems

The ability to solve a problem Divide the big task into several small sub- tasks Think more … Try to make things easier Think about how the plane looks like when it was created in 1900s. And now?

An example Use MATLAB to model an physics experiment Thomas Yang’s double-slit experiment

Young’s double-slit experiment S ： the single slit S1,S2: the double-slit pair d ： the distance between the two slits L ： the distance between the slits and the screen

Questions Why there are strips? –Because the colors on screen are differnt ； Why the colors are differnet? –Because the mixing results of the lights from the two slits are different. Why the mixing results different ？ –Because the phase of the lights are different 。 Why phase different ？ –Because the distances they pass are different 。 Why the distances different ？ –Well, well, because they are from TWO slits, not one.

The formula

How to Model? Calculate the luminance of one point on the screen Calculate the luminance of more points on the screen Turn the values of different luminance into a picture Modify ‘d’, ‘L’ to see what will happen?

How to generate a picture The concepts of a pixel? Pictures are build up by pixels. Color map

OK, let’s program … clf; figure(gcf); NClevels = 255; Br = (B/max(B))*NClevels; …

The result !

Further Consideration How to model if the light at ‘s’ is not a pure light? Can you generate a colored picture according to the wavelength you defined?

Assignment: Excises 5.18 (please refer to Example 4.7 and formula 4.5, 4.6) 6.1 (only for intensive training class)