You are on page 1of 12

MEC503 Computer Techniques February 1, 2022

Lecture 1: MATLAB REVIEW


University of Mosul Younis Najim Dep. of Mechanical Engineering

1.1 THE MATLAB ENVIRONMENT


MATLAB is a computer program that provides the user with a convenient environment for performing many
types of calculations. In particular, it provides a very nice tool to implement numerical methods. MATLAB
uses three primary windows:
1. Command window. Used to enter commands and data.
2. Graphics window. Used to display plots and graphs.
3. Edit window. Used to create and edit M-files.

Figure 1: Matlab main frame

1.2 VARIABLE
Variable can be defined as an address to a piece of computer memory where the variable value (or data) is
stored. When the variable get a new value, it replace it old value with the new one.
There are important rules in Matlab for naing a variables:
1. All names must start with a letter.
2. You can check how many characters you can use for one variable name using the command: namelengthmax
3. The allowable characters for variable name are letters, numbers, and the underscore.

1-1
1-2
4. To check whether the variable name is valid or not, use the command: isvarname.
5.Names are case sensitive. The variable x is different from the variable X
6. MATLAB has keywords. Don’t use them as variables: You can list these keywords using command:
iskeyword.
The type (or class) of a variable usually reflects the type of its value, here are some and students are required
to carefully review the other types:

1. 1. Numeric variable:

(a) double, single precision which are required for fractional data. Use realmin and realmax
to show range of values.
(b) integer: Use for signed and unsigned whole numbers.More efficient use of memory. Use intmin
and intmax to show range of values. Choose from 4 sizes (8, 16, 32, and 64 bits) using int8,
uint8, int16, int16, int32,uint32, int64, uint64.

2. String (character) variable: Data type for text. For multiple character arrays, use cell arrays.

3. Logical variable: Use in relational conditions or to test state. Can have one of two values: true or
false.

There are three main structure for the variable value (data) stored in the memory: scalar, vector, tensor. We
will discuss variable structure later on.
On the other hand, the constant refer to a value in the computer memory that does not change. There are
several constants build in Matlab such as pi.

1.3 ARITHMETIC OPERATIONS


Operations with scalar quantities are handled in a straightforward manner, similar to other computer lan-
guages. The common operators, in order of priority, are

1.4 ASSIGN VALUES to SCALAR, VECTOR, TENSOR VARIABLES

1.4.1 Scalar
A single value represented as a 1 x 1 matrix.

𝑎 = 4, In Matlab ⇒ a=4
1-3
Input is a powerful tool in matlab used to enter a value to a scalar in the program. The run will pause until
the user enter a value and press enter.

1.4.2 Vector
A list of values, arranged in either a column or a row, is a one-dimensional matrix.

3
 
𝑄 = 5 In Matlab ⇒ Q=[3;5;8]
 
 
8
 

1.4.3 Tensor
A list of values, arranged in columns and rows.

2 1 9
 
B = 7 1 3 In Matlab ⇒ B=[2,1,9;7,1,3;6,2,5]
 
 
6 2 5
 

The arithmetic operations between matrices are listed in the table below.

Operator Purpose Description


+ Addition A+B adds A and B.
- Subtraction A-B subtracts B from A
- Unary minus -A negates the elements of A.
Element-wise
.* A.*B is the element-by-element product of A and B.
multiplication
.^ Element-wise power A.^B is the matrix with elements A(i,j) to the B(i,j) power.
./ Right array division A./B is the matrix with elements A(i,j)/B(i,j).
.\ Left array division A.\B is the matrix with elements B(i,j)/A(i,j).
A.’ is the array transpose of A. For complex matrices, this does not involve
.’ Array transpose
conjugation.

1.5 RELATIONS AND LOGICAL OPERATORS


Selection and loop structures used in MATLAB depend on relational and logical operators. The relational
operators available in MATLAB are listed in the table below:
1-4
Relational Operator Interpretation
== equal to
>= greater than or equal to
> greater than
<= less than or equal to
< less than
∼= not equal to
isequal equal to (array)
isequaln Determine array equality, treating NaN values as equal

• Comparisons are either true or false, and most computer programs (including MATLAB) use the number
1 for true and 0 for false.
• WARNING: look at the difference between the equals operator (= =) and the assignment operator (=).

1.6 LOGICAL OPERATORS


The logical data type represents true or false states using the numbers 1 and 0, respectively.

Logical Operator Interpretation


& and
∼ not
| or
xor exclusive or
all Determine if all array elements are nonzero or true
any Determine if any array elements are nonzero
false Logical 0 (false)
find Find indices and values of nonzero elements
islogical Determine if input is logical array
logical Convert numeric values to logicals
true Logical 1 (true)

1.7 CONDITIONAL STATEMENTS

1.7.1 IF/END STATEMENTS


structure of if statement are described below:

1. The Simple if: A simple if statement has the following form:


if condition
statements
end
• When the comparison (a logical expression) is true, the statements between the if statement and the
end statement are executed.
• When the comparison (a logical expression) is true, the statements between the if statement and the
end statement are ignored and jumps immediately to the statement following end. example:
1-5
2. The if/else Structure The simple if allows us to execute a series of statements if a condition is true and
to skip those steps if the condition is false.
if condition
statements 1
else
statement 2
end

3. The elseif Structure The elseif function allows you to check multiple criteria while keeping the code
easy to read.
if condition 1
statements 1
elseif condition 2
statement 2
else
statement n
end

1.7.2 SWITCH and CASE STATEMENTS


The switch/case structure is often used when a series of programming path options exists for a given variable,
depending on its value. Switch and Case structure is:
switch variable
case option1
code to be executed if variable is equal to option 1
case option2
code to be executed if variable is equal to option 2
......
case option_n
code to be executed if variable is equal to option n
otherwise
code to be executed if variable is not equal to any of the options
end

1.8 LOOPS/ITERATION

1.8.1 FOR/END LOOP


Loops are very important in numerical analysis as they play the role of iterations. Loops are used to repeat
calculations many times until a specific condition is achieved. The structure is:
for index = initial value : step : Final value
Statements
1-6
end
The index takes initial value, statements is executed once then index takes initial value+ step then statement
is executed again and so on until index equals the final value.

Example 1.8.1 for k=20:5:150


T_c=k %temperature in degress
T_f=T_c*1.8+32 %this is to convert
end
for k=[10,20,50,100]
T_c=k %temperature in degress
T_f=T_c*1.8+32 end

1.8.2 WHILE/END LOOP


While loops continue until some criterion is met. The format for a while loop is: while criterion
commands to be executed
end

Example 1.8.2 k = 0;
while k<3
k = k+1
end

𝑥2 𝑥3 𝑥4 𝑛
Example 1.8.3 Find 𝑓 = 𝑥 + 2 + 3 + 4 + ... 𝑥𝑛 for 10 terms. User inputs x through input command. Use
while loop.
clc;clear; k=0;
f=0;
x=input(’Enter the value of x’);
while k<10
k=k+1;
f=f+xk̂/k;
end
disp(’f(x) is’)
disp (f)
Í (−1) 𝑘+1
Example 1.8.4 Example: Find the natural log of x, where Log(x)= 𝑛𝑘=0 𝑘
clc;clear;
k=0;
f=0;
x=input(’Enter the value of x’);
while k<2000
k=k+1;
f=f+((-1)^(k+1))/k;
end
1-7
disp(’f(x) is’)
disp (f)

1.9 OUTPUT COMMANDS


1. disp Displays contents of an array or string.

2. fprintf Performs formatted writes to screen or file. Slightly more complicated than disp. Provide
total control over the appearance of output.

fprintf syntax is:


fprintf(format-string, var,. . .)
Consider the following example:
cars = 5;
fprintf(’ There are %f cars in the parking lot’, cars);
There are 5.000000 cars in the parking lot»
The string, which is the first argument inside the fprintf function, contains a placeholder (where the value
of the variable (in this case, cars) will be inserted. The placeholder also contains formatting information.

Format Code Purpose


%s Format as a string.
%d Format as an integer.
%f Format as a floating point value.
%e Format as a floating point value in scientific notation.
%g Format in the most compact form: %f or %e.
\n Insert a new line in the output string.
\t Insert a tab in the output string.

To cause MATLAB to start a new line, you’ll need to use \n, called a linefeed, at the end of the string.

Format Code Purpose


\n linefeed.
\r carriage return (similar to linefeed).
\t tab.
\b backspace.

Example 1.9.1 Example: Write a MATALB program that convert feet [1,2,3] into inches and print the
results in a table.
feet = 1:3;
inches = feet.*12;
table = [feet;inches];
fprintf(’%4.0f %7.2f \n’,table);
1 12.00
2 24.00
3 36.00
1-8
fprintf function can be used to send formatted output to a file. First, you’ll need to create and open an output
file and assign it a file identifier (nickname). You do this with the fopen function.
file_id = fopen(’my_output_file.txt’, ’wt’);
file_id: name of the output file.

Example 1.9.2 Example: Write a MATALB program that convert feet [1,2,3] into inches and print the
results in an external file named my_output_file
feet = 1:3;
inches = feet.*12;
table = [feet;inches];
file_id = fopen(’my_output_file.txt’);
fprintf(file_id,’%4.0f %7.2f \n’,table);
fclose(file_id);

1.10 PLOTTING IN MATLAB


Plot is to draw the relation between two or more variables.
• We really need plots in mechanical engineering, for labs reports, class project, graduation project. You
can’t find a book in the mechanical engineering field without plots.
• No one likes to read numbers. Therefore, plots would be a very convenient way to figure out the relation
between these numbers.
syntax:
plot(X,Y)
• X and Y are 1D matrices (vectors) and then they must have equal length (size).
• plot(X,Y) means plotting Y versus X.

Example 1.10.1 plot sin 𝜃 for 𝜃=[1 to 360]


for i=1:360
x(i)=i;
y(i)=sind(i);
end
plot(x,y)
1-9
Example 1.10.2 x =[-2*pi:pi/10:2*pi];
y1 = sin(x);
y2 = cos(x);
p = plot(x,y1,’b-o’,x,y2,’g-*’);
title(’My first plot’)
xlabel(’Angle’)
ylabel(’sin(x) and cos(x)’)

1.11 SYMBOLIC MATHEMATICS


Mechanical engineer always works with functions of one more variables such as fluid velocity in a pipe
would be function of pipe diameter and flow rate. Now you can use MATLAB to define your function and do
apply different mathematical and algebraic operations on this function. Matlab allows symbolic operations
several areas including:
• Calculus
• Linear Algebra
• Algebraic and Differential Equations
• Transforms (Fourier, Laplace, etc)
Symbolic Math Expressions:
use the function sym or syms before the argument of mathematical function to get symbolic output:

1.11.1 DEFINING SYMBOLIC VARIABLES


To define the variable/s of the function using: » sym x you can define more variables separated by a space
such as:
syms var1 ... varN
1-10
1.11.2 DEFINING SYMBOLIC FUNCTIONS
Create symbolic functions with one and two variables:
syms s(t) f(x,y) Both s and f are abstract symbolic functions. They do not have symbolic expressions
assigned to them. To assign expression for f use:
f(x,y) = x + 2*y or f= x + 2*y for s write:
s(t)=2*sin(t)+10 or s=2*sin(t)+10

Example 1.11.1 clear;clc


syms s(t) f(x,y)
f(x,y) = x + 2*y;
s(t)=2*sin(t)+10;

Example 1.11.2 define the function f(x)=x2+9 and plot it versus x where 1𝑥 ≤ 5 ≤ 5.
syms f(x);
f(x)=x2̂+9;
x1=1:0.1:5;
M=f(x1);
plot(x1,M)

Example 1.11.3 write program to define and plot the function 𝑔(𝑡) = 3𝑠𝑖𝑛2𝑡 + (𝑐𝑜𝑠3𝑡) 2
syms g(t);
g(t)=3*sin(2*t)+cos(3*t)^2;
t1=0:pi/100:2*pi;
g1=g(t1);
plot(t1,g1,’m-.ˆ
’)
title(’Plot of g(t)=3*sin(2*t)+cos(3*t)^2’);
xlabel(’t’);ylabel(’g(t)’)
1-11
1.12 DIFFERENCES AND APPROXIMATE DERIVATIVES
The derivative can be thought of as the slope of a function or as the rate of change of the function.
syms x y;
y=x^3-4*x^2+5;
dy=diff(y,’x’,2);
disp(dy);
-------
dy =
6*x - 8
To substitute a value into a function use subs() function. The sytanx of this function is:
syntax: subs(function, variable (or expression) , value (or expression))

Example 1.12.1 clear;clc


syms x y f a b
f=x^2+2*y^2+6;
f1=subs(f,x,a)
f2=subs(f,y,b+a)
f3=subs(f,x,x^2)
f4=subs(f,y,4)
ans
f1 = a^2 + 2*y^2 + 6
f2 = 2*(a + b)^2 + x^2 + 6
f3 =x^4 + 2*y^2 + 6
f4 =x^2 + 38

1.13 INTEGRATION
let’s take the following example:
∫ 𝜋 ∫ cos 𝑥
4
Example 1.13.1 find the value of 𝑚 = 0 sin 𝑥
𝑦𝑑𝑦𝑑𝑥
clear; clc
syms x y m R
R(x,y)=y;
m=int(int(R,’y’,sin(x),cos(x)),’x’,0,pi/4);

you can see how to specify the integral limits, the function, and sequences of the two integrals.
∫ 2 ∫ √4−𝑥 2
Example 1.13.2 Example 2: Using Matlab, find 4 √
−2 − 4−𝑥 2
(4 − 𝑦 2 ) 1/2 𝑑𝑦𝑑𝑥
clear; clc
syms x y
Q=int(int((4-y^2)^0.5,’y’,-(4-x^2)^0.5,(4-x^2)^0.5),’x’,-2,2);
disp(Q)
1-12
1.14 GRADIENT, DIVERGENCE, CURL
One of the most important operator in differential calculus.

𝜕 𝜕 𝜕
∇= 𝑖+ 𝑗+ 𝑘
𝜕𝑥 𝜕𝑦 𝜕𝑥

Example 1.14.1 Suppose we have:


A=3i-8j+9k B=10i+j+5k ℎ(𝑥, 𝑦, 𝑧) = 2𝑥𝑦𝑧 3 i − 4𝑥 3 𝑦𝑧j + 𝑥𝑦 3 k 𝑓 (𝑥, 𝑦, 𝑧) = 2𝑥𝑦𝑧 3 − 5𝑥 2 𝑦 3
Find:
1. A• B
2. A× B
3. (A× B)
4. ∇ 𝑓 gradient of function f.
5. ∇ • ℎ (divergence of h)
6. ∇ × ℎ (curl of h)
7. ∇ • (∇ × ℎ)
Matlab code:
clear;clc
syms x y z
f=2*x*y*z^3-5*x^2*y^3;
h=[3*y*z^2,-4*x^3*y*z,x*y^3];
A=[3,-8,9];
B=[10,1,5];
%-----------
m1=dot(A,B)
m2=cross(A,B)
m3=dot(cross(A,B),B)
m4=gradient(f)
m5=divergence(h)
m6=curl(h)
m7=divergence(curl(h))

You might also like