Download presentation

Presentation is loading. Please wait.

Published byMonserrat Ashburn Modified over 2 years ago

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

2
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

3
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?

4
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…

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

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

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

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

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

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

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

12
The MATLAB Environment Command window Work Space Command history

13
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

14
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

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

16
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

17
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.

18
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.

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

20
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

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

22
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(?)

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

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

25
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

26
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

27
Assignment: Excises 2.1, 2.2, 2.3 2.4

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

29
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

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

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

32
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.

33
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.

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

35
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)

36
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.

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

38
Assignment: Excises 2.6, 2.7, 2.8, 2.9

39
MATLAB & Its Applications In Engineering

40
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

41
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).

42
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.

43
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.

44
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.

45
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

46
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

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

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

49
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.

50
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

51
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.)

52
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

53
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

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

55
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.

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

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

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

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

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

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

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

63
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)');

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

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

66
plot3

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

68
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')

69
subplot

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

71
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.

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

73
Logarithmic scales semilogx(x,y)

74
Logarithmic scales loglog(x,y)

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

76
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

77
Top-down Design Flow

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

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

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

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

82
Logical operators & | xor ~

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

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

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

86
Example using if construct score = input(‘please input your score: ‘); if score >= 90 grade = ‘Excellent’; elseif score >= 70 grade = ‘Good’; elseif score >= 60; grade = ‘Passed’; else grade = ‘Failed’; end disp(grade);

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

88
Example using switch construct password = input(‘please input your password: ‘); switch password case ‘matlab’ privilege = ‘WRITE_ONLY’; case ‘pld’ privilege = ‘READ_ONLY’; otherwise privilege = ‘FORBIDDEN’; end

89
Assignment: Excises 3.2, 3.3, 3.4, 3.5

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

91
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

92
Top-down Design Flow

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

94
Arithmetic operators + - * /

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

96
Logical operators & | xor ~

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

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

99
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

100
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

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

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

103
Logical functions isequal( ) Examples

104
Logical functions isempty ( ) Examples

105
Logical functions isinf ( ) Examples

106
Logical functions isnan ( ) Examples

107
Logical functions isnumeric ( ) Examples

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

109
Example using if construct score = input(‘please input your score: ‘); if score >= 90 grade = ‘Excellent’; elseif score >= 70 grade = ‘Good’; elseif score >= 60; grade = ‘Passed’; else grade = ‘Failed’; end disp(grade);

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

111
Example using switch construct

112
Assignment: Excises 3.2, 3.3, 3.4, 3.5

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

114
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

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

116
The while construct while Repeatedly execute statements while condition is true

117
The while construct Syntax while expression … … code_block end

118
Example using while construct Example ATTENTION

119
Example using while construct The result

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

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

122
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

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

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

125
Example using for construct Example

126
Example using for construct Example

127
Difference between while and for

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

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

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

131
Debug Break debug break.avi Continue continue.avi

132
Assignment: Excises 4.1, 4.3, 4.4

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

134
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

135
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.

136
The structure of a complicated program

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

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

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

140
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;

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

142
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”[ ]”

143
A simple function

144
The result

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

146
User-Defined Functions

147
Function file+subfile

148
User-Defined Functions Inline +command/function file

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

150
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)

151
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?

154
Assignment: Excises 5.9, 5.23

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

156
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

157
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?

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

159
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

160
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.

161
The formula

162
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?

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

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

165
The result !

166
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?

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

Similar presentations

OK

MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.

MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.

© 2018 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Ppt on meeting etiquettes Ppt on climate change Ppt on cse related topics about work Detail ppt on filariasis ppt Ppt on singular plural for grade 1 Ppt on javascript events handling Ppt on regional transport office lucknow Ppt on 4-stroke petrol engine Ppt on 14 principles of henri fayol unity Ppt on ancient 7 wonders of the world