0% found this document useful (0 votes)
5 views28 pages

MEEN 2240 Programming For Mechanical Engineers

Basic intro for programming for mechanical engineers during my time at Uni

Uploaded by

redlord183
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views28 pages

MEEN 2240 Programming For Mechanical Engineers

Basic intro for programming for mechanical engineers during my time at Uni

Uploaded by

redlord183
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

MEEN 2240

PROGRAMMING FOR
MECHANICAL ENGINEERS

Instructor: Dr. Yunwei Xu


Dept of Mechanical Engineering
University of North Texas
Chapter 1
Introduction to MATLAB

i. The MATLAB Desktop Environment (s5-s6)

ii. Variables and Assignment Statement (s7-s9)

iii. Type ranges and Type Casting (s10-s12)

iv. Numerical Expressions (s13-s14)

v. Formatting (s15)

vi. Built-in Numerical Functions & Math Operators (s16-s23)

Copyright © 2020 Yunwei Xu, PhD 2


MATLAB Functions
and Commands
MATLAB
Operators

Copyright © 2020 Yunwei Xu, PhD 3


Introduction

• Very powerful software package

• Many mathematical and graphical applications

• Has programming constructs

• Also has many built-in functions

• Can use interactively in the Command Window, or write


your own programs

Copyright © 2020 Yunwei Xu, PhD 4


MATLAB Installation and Textbook Requirement

• Click on the link below and enter your UNT email ID (.@my.unt.edu)
https://www.mathworks.com/academia/tah-support-program/eligibility.html

• You will receive email for creation of MathWorks account. Enter your credentials and
follow the instructions for downloading and activating the software.

• Kindly let me know if you have any questions.

• MATLAB – A Practical Introduction to Programming and Problem Solving, 5th Edition,


Elsevier, 2018
Stormy Attaway
ISBN-13: 978-0128154793

Copyright © 2020 Yunwei Xu, PhD 5


MATLAB Desktop Environment
Working Directory:
shows location where you are currently
working. Files will be saved here.

Command Window: Workspace:


Current Folder:
can use for simple shows information of all
shows files in current
calculations, to run variables
working directory
programs, access help
menu, etc. Command History:
shows recent commands
entered in the command
window

Copyright © 2020 Yunwei Xu, PhD 6


MATLAB Desktop Environment

Layout: Arrange the windows and positioning by going to here Preference: MATLAB appearance can be changed
on the toolbar by going here, for instance:
• Colors – to change the background and font
colors
• Fonts – to modify font type and size

Copyright © 2020 Yunwei Xu, PhD 7


Variables and Assignment Statement
• variables: to store values
• one way to put a value in a variable is with an assignment statement
• general form:
variable = expression
• The order is important
• variable name on the left
• the assignment operator “=” (Note: this does NOT mean equality)
• expression on the right

Copyright © 2020 Yunwei Xu, PhD 8


Variables and Assignment Statement

Example 1:

i. The value 3 is assigned to the


variable mynumber.

ii. mynumber is changed to have


the value of the expression 4+2
(or 6).

iii. mynumber is changed to 6+1 (or


7).

iv. Semi-colon (;) to prevent this


repetition, no result is shown.

Note: MATLAB goes from top to


v. but double-chick “mynumber” in Workspace, result can be found under the
bottom when doing calculations
variable (MATLAB only stores/uses the last calculated value).

Copyright © 2020 Yunwei Xu, PhD 9


Variables Names
 Names must begin with a letter of the alphabet

 After that names can contain letters, digits, and the underscore character _

 MATLAB is case-sensitive:

mynum ≠ MYNUM ≠ Mynum

 Use informative names


• Names should make sense!
• Generic names like abc or number are difficult to remember
• Think about writing a code and then coming back to it

three months from now… will you remember what the


variables are?
If not, rename them!
 clearvars: to delete all variables

 clear: to delete all variables and functions

 clc: clears out variables and also commends

 The commands who and whos will show variables

Copyright © 2020 Yunwei Xu, PhD 10


Types or Class
 Every expression and variable has an associated type, or class

 Real numbers: single, double

 The default type for numbers is double

 Integer types: numbers in the names are the number of bits used to store a value of that

type

 Signed integers (store sign and integer): int8, int16, int32, int64

 Unsigned integers (only store integer, integer can only be positive): uint8, uint16,
uint32, uint64

 Single characters and character vectors: char (e.g., ‘abc’)

 Strings of characters: string (e.g., “hello”)

 True (1)/false (0): logical

 Show all variables: who and whos

Copyright © 2020 Yunwei Xu, PhD 11


Types or Class

Binary system
only store 0s or 1s
Decimal system

Int 8

0 0 0 0 0 1 0 0 =4
Sign Value
bit bits

Copyright © 2020 Yunwei Xu, PhD 12


Type Casting

• Need to switch from a


double(double precision) to an
integer?
• Use type casting!
• Use the type names to switch from
one to the other

Example 2:

Having a variable num equal to 2.6


(with double precision), want to
convert 2.6 to an 8-bit integer?

Type casting converts num to an


integer with a value of 3.

Copyright © 2020 Yunwei Xu, PhD 13


Numerical Expressions

 Expressions can contain:


values
variables (that have already been initialized before being used)
operators
built-in functions
parentheses

 Operators include:
+ addition
- negation, subtraction
* multiplication
/ division (divided by e.g. 10/5 is 2)
\ division (divided into e.g. 5\10 is 2)
^ exponentiation (e.g. 5^2 is 25)

 Scientific or exponential notation:


use e for exponent of 10 raised to a power
 e.g. 3e5 means 3 * 10^5

Copyright © 2020 Yunwei Xu, PhD 14


Operator Precedence

 Similar with algebra, operators within MATLAB have precedence over


others

 Precedence list (highest to lowest) so far:

() parentheses

^ exponentiation

- negation

*, /, \ all multiplication and division

+, - addition and subtraction

 Nested parentheses: expressions in inner parentheses are evaluated first

 Be careful when creating long expressions

Copyright © 2020 Yunwei Xu, PhD 15


Formatting
• format changes how values are displayed:

• short – 4 digits to right of decimal

• long – 15 digits to right of decimal

• longg (take out scientific notation)

• Scientific or exponential notation:

• use e

• Example: 8e7 equates to 8 * 107

• Have a long expression?

• use the ellipsis (…)


• allows all code to be seen without scrolling to
the right

• Other format options:


• Type: help format

Copyright © 2020 Yunwei Xu, PhD 16


Built-in Numerical Functions
 There are large number of built-in functions in
MATLAB
 Built-in functions allow the user to complete a
range of tasks quickly and easily
 There are functions that perform simple
calculations
 such as: sin (radian), cos, sind (degree),
abs, plus
 There are functions that perform complex
calculations
 such as a numerical integration or
curve fitting
 To see a list of help topics, type “help” at the
prompt:
>> help
 To find out about a particular function, e.g. sin:
>> help sin

Copyright © 2020 Yunwei Xu, PhD 17


Using Numerical Functions

 To use a function, you call it

 To call a function, give its name followed by the argument(s) that are passed to it in
parentheses

 Many functions calculate values and return the results

 For example, to find the absolute value of -5


argument

function name
returns result

 The name of the function is “abs”

 One argument, -5, is passed to the abs function

 The abs function finds the absolute value of -5 and returns the result, 5

Copyright © 2020 Yunwei Xu, PhD 18


Numerical Functions
• Trig functions:
• sin, cos, tan, sec, csc, cot
• Arguments must be in radians
• sind, cosd, tand, secd, cscd, cotd
• Arguments must be in degree
• Arc functions: asin, acos, atan, asec, acsc, acot
• Returns angle in radians
• Exponential functions:
• exp – exponential
• exp (-2) equates to e −2
• log – natural log
• log (1) equates to ln 1
• sqrt – square root
• sqrt (4) equates to 4

Copyright © 2020 Yunwei Xu, PhD 19


Numerical Functions

• Random Numbers
• call rand – generate one random real number in the open interval (0,1)
• call randi(imax) to generates a random integer in the range from 1 to imax
• how to generate one random real number within (0, 10)?

Copyright © 2020 Yunwei Xu, PhD 20


Numerical Functions

• Complex functions:
• conj: complex conjugate
• imag: complex imaginary part
• real: complex real part
• Rounding functions:
• round: round towards nearest integer
• ceil: rounds up towards +∞
• floor: rounds down towards −∞
• fix: rounds towards zero
• sign: gives + or -

Copyright © 2020 Yunwei Xu, PhD 21


Characters and Strings
 A character is a single character in
single quotes: ‘ ’
 All characters in the computer’s
character set are put in an order
using a character encoding
 In the character encoding
sequence, the letters of the
alphabet are in order, e.g. ‘a’
comes before ‘b’
 Common encoding ASCII has
128 characters, but MATLAB
can use a much larger encoding
sequence
 The character set includes all letters
of the alphabet, digits, punctuation
marks, space, return, etc.
 Character vectors are sequences of
characters in single quotes, e.g.
‘abc’
 Strings are sequences of characters
in double quotes: “ ”, e.g. “hello”
Copyright © 2020 Yunwei Xu, PhD 22
Logical – Relational Expressions
 The relational operators in MATLAB are:

> greater than

< less than

>= greater than or equals

<= less than or equals

== equality

~= inequality

 The resulting type is logical, 1 for true or 0 for false

 The logical operators are:

|| or for scalars

&& and for scalars

~ not

 Also, xor function which returns logical true if only one of the arguments is true

Copyright © 2020 Yunwei Xu, PhD 23


Constants

• Constant – known value that does not change

• MATLAB has built-in constants


• pi: 𝜋

• i or j: −1

• Inf ,-Inf: 
• NaN: not a number
• You don’t want to see this!
• Means your tried to divide by zero.

Copyright © 2020 Yunwei Xu, PhD 24


Getting Help

• To see a list of help topics,


use the command help
>> help

• To find out about a particular


function like absolute value:
>> help abs

Copyright © 2020 Yunwei Xu, PhD 25


Practices
Example 3: Example 4:

Calculate the area moment of inertia for Determine the final displacement after
circular area as below, with the radius 20 seconds of a car that has an initial
(r) is 2 m. velocity of 40 m/s and a deceleration of
1 1m/s2. Initial displacement is 300 m.
Ix =  r4
4 The kinematic equation is:

1
s = s0 + v0t + at 2
2

Change to short format

Copyright © 2020 Yunwei Xu, PhD 26


Practices
Example 5: Example 6:
Calculate the cosine of 60⁰. Test out the various rounding function for π.

Method 1: calling the function cosd


and 60 is the input argument.

Method 2: calling the function cos,


but convert 60 degrees into radians,
to be the input argument.

Copyright © 2020 Yunwei Xu, PhD 27


Quiz 1
1. To install MATLAB on your laptop.

2. The combined resistance RT of three resistors R1, R2, and R3 in parallel is given by
1
RT =
1 1 1
+ +
R1 R2 R3
Determine the RT if
R1 = 45 
R2 = 55 
R3 = 65 
round your result towards nearest integer.

3. In special relativity, the Lorenta factor is a number that describes the effect of speed on various physical
properties when the speed is significant relative to the speed of light. Mathematically, the Lorentz factor is given
as: 1
=
v2
1−
c2

Use 3 × 108 m/s for the speed of light, c. Create variable for c and the speed v and from them a variable lorentz for
the Lorentz factor. Determine the Lorentz factor if the speed v = 50 m/s.

4. Use the deg2rad function to convert 90 degrees to radians.

Copyright © 2020 Yunwei Xu, PhD 28

You might also like