Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Introduction to Programming with MATLAB in Mechanical Engineering, Assignments of Computer Science

This document from the Mechanical Engineering Department at UET Lahore, authored by Dr. Zia R Tahir, provides an introduction to MATLAB for engineering students. It covers basic operations, variables, vectors, matrices, structures, and the use of MATLAB as a numerical calculator. It also introduces functions, scripts, and control flow in programming.

Typology: Assignments

2020/2021

Uploaded on 04/25/2022

abdullah-arshad-5
abdullah-arshad-5 🇵🇰

3 documents

1 / 72

Toggle sidebar

Related documents


Partial preview of the text

Download Introduction to Programming with MATLAB in Mechanical Engineering and more Assignments Computer Science in PDF only on Docsity! Dr. Zia Tahir R Problem Solving in Engineering with MATLAB Department Engineering Mechanical Introduction to Matlab Mechanical Lahore UET Department, Engineering Problem Solving in Engineering with MATLAB Zia Dr Tahir R Introduction to Matlab  Outline • The Matlab Environment • Basic operations • Variables • Vectors • Definition • Basic operations • 2D Plots • Access information • Matrices • Definition • Basic operations • Access information • Structures 2 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Definition of variables • To create a variable assign a value to a name using = >> r = 2.131 • Use ; at the end to suppress the output >> r = 2.131; • The name of variables is case sensitive >> r = 2.131; >> R = 90.121; • Variables can be created using expressions involving other variables: >> L = 2*pi*r; >> A = pi*r^2 • The variables appear in the workspace. • Note that “pi” is a reserved word. There is no need to define it. 5 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Matlab built-in functions • A great number of functions is available • Trigonometric: • sin, cos, tan, ... (angle in radians) >> sin(pi/2) • sind, cosd, tand, ... (angle in degrees) >> cosd(45) • asin, acos, sinh, ... >> asin(-1) • Exponential: • exp >> exp(2.1) • Logarithms • log, log2, log10 >> log10(100) • Square root • sqrt >> sqrt(9.5) • Rounding: • ceil, floor, round,... >> ceil(7.1) • Check the Matlab help for these functions 6 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Use Maltab help! • No need to remember all functions: • lookfor • No need to remember how to use all functions: • help • Extensive use of Matlab product help is strongly recommended, specially at the early stages of your learning! 7 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Vectors • Ways to build large vectors without writing all the components: 4. Function ones: >> y = ones(3,1) ; Vector of 3 rows and 1 column fill in with ones 5. Concatenate vectors of the same type (row or column) Row vectors: >> v = [1, 8, 4]; >> w = [7, 9, 1, -4]; >> z = [v, w]; 10 Column vectors: >> v = [1; 4]; >> w = [7; 9; -4]; >> z = [v; w]; Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Operations with vectors • Addition and subtraction of vectors of the same type (row or column) and length >> v = [8, 2, 9]; >> w = [-2, 0.1, 7]; >> v + w • Scalar product of a row vector and a column vector >> v = [6, 3, 1]; >> w = [4; 2; 0]; >> v*w • Functions applied to vectors >> v = [30 60 90]; >> w = sind(v) This means w = [ sind(30), sind(60), sind(90)]; 11 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Operations with vectors – Usual mistakes • Addition and subtraction with vectors of different type (row or column) and/or length >> v = [6, 3, 1]; >> w = [4; 2; 0]; >> x = [-1; 0; 10; 3]; >> v + w >> w + x • Scalar product of non matching vectors >> v = [6, 3 1]; >> w = [4 2 0]; >> v*w >> v*transpose(w) • Note the use of the function transpose • When something is not working: read the error message! 12 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Basic 2D plots Adding information >> title('Function plots') >> xlabel('x (angle)') >> ylabel('y') >> grid on Several plots in one figure: >> hold on >> z = sind(x); >> plot(x,z, 'k-s') >> legend('cosinus','sinus') “hold on” Allows us to plot data in an existing figure without losing the previous plot. If not, only the last plot is shown 15 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from vectors  The name of the vector followed by the component/s to access in between brackets >> v = [10, -12, 35, 7.5, 9 , 12, 4]; >> v(3)  The result is a scalar 1 2 3 4 5 6 7 10 -12 35 7.5 9 12 4 16 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from vectors  The name of the vector followed by the component/s to access in between brackets >> v = [10, -12, 35, 7.5, 9 , 12, 4]; >> v(3)  We can access several components using the semicolon >> v(1:5)  The result is a row vector 1 2 3 4 5 6 7 10 -12 35 7.5 9 12 4 17 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from vectors  The name of the vector followed by the component/s to access in between brackets >> v = [10, -12, 35, 7.5, 9 , 12, 4]; >> v(3)  We can access several components using the semicolon >> v(1:5) >> v(1:2:5), v(5:-2:1)  Even if the components don’t follow a pattern >> v([1,4,6]) 1 2 3 4 5 6 7 10 -12 35 7.5 9 12 4 20 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from vectors  But sometimes, we don’t know a priori where the information is • Obtain the maximum value in a vector >> v = [10, -12, 35, 7.5, 9 , 12, 4]; >> a = max(v) 1 2 3 4 5 6 7 10 -12 35 7.5 9 12 4 21 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from vectors  But sometimes we don’t know a priori where the information is • Obtain the maximum value in a vector >> v = [10, -12, 35, 7.5, 9 , 12, 4]; >> a = max(v) • But where is the maximum? • >> [a, position] = max(v) 1 2 3 4 5 6 7 10 -12 35 7.5 9 12 4 22 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Matrices • Matrices defined concatenating existing vectors and/or matrices • The dimensions must be consistent >> v = [1 2]; >> w = [-1 0]; >> A = [v; w] >> v = [7; 2]; >> w = [0; 5]; >> B = [v, w] 25 >> v = [1 2]; >> w = [-1 0]; >> x = [3, 7]; >> y = [6; 4; 9]; >> A = [[v; w; x], y] Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Matrices • Matrices defined concatenating existing vectors and/or matrices • The dimensions must be consistent >> A = [1 0; 7 2]; >> B = [-1 3; 4 2; 9 6]; >> C = [A; B] 26 >> A = [1 0; 7 2]; >> B = [-1 3; 4 2; 9 6]; >> C = [[A; B], [transpose(B); eye(3)]] Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from matrices  The name of the matrix followed by the components to access in between brackets and separated by a comma  First index indicate row, second index indicate column >> A = [10, 21, 13, 1; 0, 35, 4, -8; -1 7 9 2; -4 4 5 6]; >> A(2 , 3)  The result is a scalar 1 2 3 4 1 10 21 13 1 2 0 35 4 -8 3 -1 7 9 2 4 -4 4 5 6 27 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from matrices  The name of the matrix followed by the components to access in between brackets and separated by a comma  We can access to several components using the colon >> A = [10, 21, 13, 1; 0, 35, 4, -8; -1 7 9 2; -4 4 5 6]; >> A([1,3] , 4)  The result is a column vector 1 2 3 4 1 10 21 13 1 2 0 35 4 -8 3 -1 7 9 2 4 -4 4 5 6 30 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from matrices  The name of the matrix followed by the components to access in between brackets and separated by a comma  We can access to several components using the colon >> A = [10, 21, 13, 1; 0, 35, 4, -8; -1 7 9 2; -4 4 5 6]; >> A([1,4] , 3:4)  The result is a matrix 1 2 3 4 1 10 21 13 1 2 0 35 4 -8 3 -1 7 9 2 4 -4 4 5 6 31 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Accessing information from matrices  But sometimes we don’t know a priori where the information is • Extract the maximum value in a matrix >> A = [10, 21, 13, 1; 0, 35, 4, -8; -1 7 9 2; -4 4 5 6]; >> z = max(A) Result: z = [10 35 13 6];  The result is a vector containing the maximum of each column operating along all rows 1 2 3 4 1 10 21 13 1 2 0 35 4 -8 3 -1 7 9 2 4 -4 4 5 6 32 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Matlab  Structures  Structures are variables that contain other variables as fields  Use variable.field to define a field. For instance: >> person.age = 30; >> person.height = 167; >> person.weight = 67;  To access all the fields write the name of the structure >> person  To access a particular field write the name of the variable dot name of the field >> person.height 35 Dr. Zia Tahir R Problem Solving in Engineering with MATLAB Introduction to Programming 1 Functions and S cripts Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Outline • The Matlab editor • Scripts • How to create a script • How to execute a script • Functions • Inputs (arguments) • Outputs (results) • How to create a function • How to execute a function • Tips for designing good programs • Presenting the results on the screen 37 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Example of a script  The Matlab editor is interactive. It uses colours to highlight Warnings and Errors  In fact, forgetting the semicolon at the end of a instruction is highlighted with a warning colour on the equal symbol of lines 15 and 18 40 • Comments (lines starting with %), in green, are not Matlab instructions • Note that the semicolon has been supressed in lines 15 and 18 to allow the output to be seen on the screen. We will learn a better way of presenting the results on the screen by the end of this lesson Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Script execution • Once the file is saved, you can execute a script by • Writing the name in the command window (without no extension) • Clicking “Run” in the Matlab editor 41 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  To create a function • Create a new M-file by choosing “New script”** • The Matlab editor will open (blank page) • Write the function header • function outputs = functionName(inputs) Starts always with the word “function” that will be highlighted in blue in the Matlab editor • Write a set of Matlab instructions to be executed in order. The instructions are designed to obtain the outputs using the inputs • Save the M-file by choosing “Save” and name as functionName.m THE NAME OF THE M-FILE MUST BE EQUAL TO THE NAME OF THE FUNCTION **Note that you can also create a Matlab function by choosing “New Function”. The function header will be created but you still have to name the function and provide the inputs and outputs 42 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Function example – Several inputs and outputs • A function that, given the height and radius of a cylinder return its area and volume • Name: areaVolumeCylinder.m • Inputs: Radius (R) and Height (H) • Outputs: Area (A) and Volume (V) • Note that: • Inputs are separate by commas and in between brackets (R,H) • Outputs are separated by commas and in between square brackets [A,V]  Following the same syntax, functions with an arbitrary number of inputs/outputs can be defined 45 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Function execution – Several inputs and outputs • Once the file is saved, you can execute (use) a function by • Writing the name in the command window providing names for the inputs and outputs • Note that the order is important!! • 1.123 will be assigned to R (first input) and 0.9129 to H (second input) • Analogously, the result A is assigned to area (first output) and the result V to the variable volume (second output) 46 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Tips for designing good programs (1) • Sketch the structure of your program before starting Matlab • Decide how many functions and scripts you need • Is never a good idea to repeat formulas. Define functions instead and use them whenever is necessary • Decide the name of the files. Do not underestimate this part, it is important. The names should already indicate what the program is meant to do • The sketch should indicate the workflow: which functions are called by other Matlab files • Write each script or function in a separate Matlab file (M-file) • It is possible to write several functions inside a single M-file but you should avoid this practice (at least in this module) • Use meaningful names for the variables • Regularly introduce comments that help to understand what the program is doing 47 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  One example from scratch  Note the structure, the names of the variables and files and the comments 50 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Presenting the results on the screen  To write a sentence on the screen use disp • Example: >> disp('Hello world!') • The sentence between apostrophes  To write a sentence that contains variable values use fprintf • Example: >> a=436; >> fprintf('The current value of a is %d. It is an integer.', a) • The sentence between apostrophes • To write a variable in the sentence use %d if the variable is integer • After the apostrophe, introduce a comma and the name of the variable • When the sentence is written, Matlab will change the symbol %d by the current value of the variable a 51 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 1  Presenting the results on the screen  To force a line break after the use fprintf use \n. Examples: >> fprintf('The current value of a is %d. It is an integer.', a) >> fprintf('The current value of a is %d. It is an integer.\n', a) >> fprintf('The current value of a is %d.\nIt is an integer.\n', a) 52 Dr. Zia Tahir R Problem Solving in Engineering with MATLAB Introduction to Programming 2 Control F low and L oops Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Outline • Control flow • Take decisions • Relational and logical operators • Loops • Repeat instructions many times • Fill in vectors • Iterate until a condition is satisfied 56 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Control flow  So far, we have designed simple programs where all the instructions written in the M-file are executed in order  What happens when, depending on the value of a variable, different instructions should be executed?  Examples: • Speed camera: Takes a photo if your speed is higher than the one permitted in that road • Using your mobile: If you write the correct PIN you can access otherwise you receive a message and you cannot access 57 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Control flow  How do we check if a condition is satisfied?  Relational and logical operators: • == Equal to • > Greater than • < Less than • >= Greater than or equal to • <= Less than or equal to • ~= NOT equal to 60 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Control flow  If we have several conditions and different instructions to be executed in each case we use if (condition1) instructions1 elseif (condition2) instructions2 else instructions3 end 61 How it works? • If condition1 is true, instructions1 are executed and no more conditions are checked • If condition1 is false, condition2 is checked. If conditions2 is true, instructions2 are executed and no more conditions are checked • If conditions1 and condition2 are false, instructions3 are executed Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Control flow  Example: • Create a function that, given a number returns one of the following three messages • The number is less than 10. • The number is greater than (or equal to) 10 but less than 20. • The number is greater than (or equal to) 20.  Sketch 62 FUNCTION Name: checkNumber.m Input • Number Output • No output result, just a message on the screen depending on the input Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Loops  for loops allow us to repeat certain instructions reducing the amount of writing significantly  Syntax: for counter=initial:step:final instruction end  Preliminary example: • Write a Matlab program that writes on the screen a sentence 100 times • Remember: 1:N is equivalent to “1:1:N” (initial:step:final) 65 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Loops  Preliminary example 2: • Write a Matlab program that writes on the screen the odd numbers from 1 to 23 66 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Loops  Example 1: Write a function in Matlab that, given a positive integer n computes the sum  Note how the result is first initialised to be zero.  Then each term is added to the previous value, so we accumulate the final value of the sum 67 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Loops  Fill in a vector example: Plot the function below between [-3,0] 70 Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Loops  Iterate until something happens  Example: The pressure (p) on a can depends on the temperature (T) according to the law p(T)=0.00105T2 + 0.0042T + 1.352 Create a program that, starting with a temperature of 15ºC, and increasing the temperature by 0.5ºC, checks when the pressure is more than 3.2atm. The program should end when this value is detected  Sketch 71 MAIN FILE Data • Starting value of temperature • Increment of temperature • Maximum tolerated pressure Computations • Calling the function canPressure.m FUNCTION Name: canPressure.m Input • T: temperature Output • P: pressure Mechanical Lahore UET Department, Engineering Problem Tahir R Zia Dr MATLAB with Engineering in Solving Introduction to Programming 2  Loops  Iterate until something happens  The command break stops the execution of the loop, so we are not actually iterating until T=Tfinal 72
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved