0% found this document useful (0 votes)
53 views

Introduction To Matlab and Manipulation of Functions

This document provides an introduction to MATLAB and covers various fundamental concepts including: 1. Opening MATLAB and using the command window to define variables, perform arithmetic, and use built-in functions. 2. Creating and manipulating arrays (called vectors in MATLAB) using indexing and functions like linspace. 3. Plotting common functions like trigonometric, exponential, and polynomial functions to demonstrate MATLAB's plotting capabilities. Hyperbolic functions and decomposing functions into even and odd parts are also discussed. 4. The document introduces key concepts through examples typed directly into the command window and concludes by mentioning the MATLAB editor for writing script files.

Uploaded by

NoorLiana Mahmud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Introduction To Matlab and Manipulation of Functions

This document provides an introduction to MATLAB and covers various fundamental concepts including: 1. Opening MATLAB and using the command window to define variables, perform arithmetic, and use built-in functions. 2. Creating and manipulating arrays (called vectors in MATLAB) using indexing and functions like linspace. 3. Plotting common functions like trigonometric, exponential, and polynomial functions to demonstrate MATLAB's plotting capabilities. Hyperbolic functions and decomposing functions into even and odd parts are also discussed. 4. The document introduces key concepts through examples typed directly into the command window and concludes by mentioning the MATLAB editor for writing script files.

Uploaded by

NoorLiana Mahmud
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

VEB1062 COMPUTATIONAL METHODS FOR ENGINEERS

INTRODUCTION TO MATLAB AND MANIPULATION OF


FUNCTIONS
Mohamed Latheef
14.03.26
[email protected]

1
REVISION OF
FAT0015 FUNDAMENTALS OF PROGRAMMING I

2.1
GENERAL CONCEPTS - IDE

2.2
GENERAL CONCEPTS - OTHERS
Basics of computers
Software and hardware
Binary number system
Pseudocode, ow charts
Etc.

2.3
VARIABLES
var
radius : real;
name : string;
loopvar : integer;

Declares 3 variables
Two numbers (real and integer) and a string
Required decleration before use - feature of statically typed language

2.4
BUILT-IN FUNCTION AND LOGICAL OPERATORS
Lots of built in functions such as cos() are available
Concept of logical operators
(5 > 6) AND (2 <= 3)

What do you think this does?

2.5
DECISION MAKING
Logical operators were used to make decisions
// score is a real
score := 30;

if score >= 80 then


writeln('Congratulations! Distinction!')
else if score >= 40 then
writeln('You have passed')
else
writeln('You have failed. Please see me!')

2.6
LOOPING
A number of looping constructs including for and while were introduced
What does the following do?
var
i : integer;

begin

for i := 1 to 10 do
writeln(i);

end

2.7
ARRAYS
Arrays were introduced as a way of storing the same data type
contiguously and address using a single variable
var
i : integer;
five_times : array[1 .. 10] of real

begin

for i := 1 to 10 do
five_times[i] = 5*i;

for i := 1 to 10 do
writeln(five_times[i]);

end

2.8
PROCEDURES AND FUNCTIONS
Procedures and functions that act like built in functions were introduced
Procedure Print3Names(n1, n2, n3 : string)
begin
writeln('Some of the favourite characters');
writeln('of your lecture is:');
writeln('Names: ', n1 + ' ' + n2 + ' ' + n3);
end

begin
Print3Names('Khaleesi', 'Walt', 'Frank');
end.

2.9
OTHER TOPICS
Formatting output
Dealing with les
Input
Output
Although not revised, they will be useful in MATLAB too

2 . 10
MATLAB:
BASICS

3.1
WHAT IS IT?
A high level programming environment
Designed for maths intensive programming
Read ideal for engineers and scientists
Good graphing
Most of the algorithms/functions for data analysis in built
Clients include

3.2
OPENING MATLAB
3.3
COMMAND WINDOW

Majority of what follows will be typed up directly in the command window


3.4
VARIABLES

>> 1 + 2
ans =
3
>> a = 1;
>> b = 2;
>> c = a + b
ans =
3

Notice that we didn't declare the types of a and b

3.5
ARRAYS
In MATLAB, arrays are called vectors
A vector containing numbers 1 to 8 maybe de ned in the following way
v = [1,2,3,4,5,6,7,8];
v = 1:1:8;

The second line uses ':' operator


The general syntax goes start:step:end
Create numbers from 1 to 8 in steps of 1

3.6
ARRAYS: WORKSPACE
Once that was executed, the workspace and variable explorer looks as
follows

3.7
ARRAYS: INDEXING
Indexed using array(index)
Index starts at 1 and goes upto the number of elements
1:length(vector)
For the previous vector, to change the fourth element to 4.8
>> v(4) = 4.8
v =
1.0 2.0 3.0 4.8 5.0 6.0 7.0 8.0

3.8
BUILT-IN FUNCTIONS: LINSPACE()
All the mathematical functions you can think of (and more) are available
When creating vectors, linspace() is a very useful function
General form is
>> linspace(start, end, NElements)

To create a vector with 40 equally spaced numbers from 10 to 30 the


following maybe used
>> v = linspace(10, 30, 40);

3.9
AN ASIDE ON HELP()
MATLAB comes with comprehensive help documentation
Call it with help commandname as shown for linspace
>> help linspace
linspace Linearly spaced vector.
linspace(X1, X2) generates a row vector of 100 linearly
equally spaced points between X1 and X2.

linspace(X1, X2, N) generates N points between X1 and X2.


For N = 1, linspace returns X2.

Class support for inputs X1,X2:


float: double, single

See also logspace, colon.

This is your friend, do use it extensively

3 . 10
TRIGONOMETRIC FUNCTIONS
We all know trigonometric functions, they repeat themselves
They are available as built in functions
Just call by cos(variable)
Here variable can be a number or even an array
Performing
>> x = [0, 1, 3, 4];
>> y = cos(x);

Actually results in

3 . 11
TRIGONOMETRIC FUNCTIONS: PLOTTING THEM
Let's plot sin() and cos() over 2 cycles
>> x = linspace(0, 4*pi, 100);
>> y1 = sin(x);
>> y2 = cos(x);
>>
>> plot(x,y1,'b-', x,y2,'r--')

Resulting in

3 . 12
ON THE PLOT() COMMAND
The general format for this command is
>> plot(data1_X,data1_Y,linestyle, data2_X, data2_Y, linestyle

Here linestyle is a string


First character is the colour
Second and third characters give the line style
In MATLAB, strings are vectors of characters
For example
>> linestyle = 'b--';
>> linestyle(1)
ans =
'b'
>> linestyle(2)
ans =
'-'
>> linestyle(3)
ans =
'-'

3 . 13
EXPONENTIAL FUNCTION
y = exp(x) is another important function in engineering
Appears as a solution of some of the di erential equations in Civil
engineering
De ning and plotting over −1 ≤ x ≤ 1 is done as
>> x = linspace(-1, 1, 100);
>> y = exp(x);
>> plot(x,y)

Resulting in

3 . 14
EVEN AND ODD FUNCTIONS (1)
As you have learned in foundation pre-calculus, an even function is
f (−x) = f (x)

Similarly, an odd function is


f (−x) = −f (x)

As you also learned in foundation pre-calculus, any function f (x)


maybe decomposed into an even and an odd function

3 . 15
EVEN AND ODD FUNCTIONS (2)
The even part, fe (x) is given by
f (x) + f (−x)
fe (x) =
2
The odd part, fo (x) is given by
f (x) − f (−x)
fo (x) =
2

3 . 16
HYPERBOLIC FUNCTIONS (1)

For the exponential function, the even part gives a new function
exp(x) + exp(−x)
fe (x) = cosh(x) =
2

De ning and plotting over −1 ≤ x ≤ 1 is done as


>> x = linspace(-1, 1, 100);
>> y1 = cosh(x);
>> y2 = 0.5*exp(x);
>> y3 = 0.5*exp(-x);
>>
>> plot(x,y1, x,y2,'--', x,y3,'--')

3 . 17
HYPERBOLIC FUNCTIONS (1)

Resulting in

3 . 18
HYPERBOLIC FUNCTIONS (2)

For the exponential function, the odd part gives a new function
exp(x) − exp(−x)
fe (x) = sinh(x) =
2

De ning and plotting over −1 ≤ x ≤ 1 is done as


>> x = linspace(-1, 1, 100);
>> y1 = sinh(x);
>> y2 = 0.5*exp(x);
>> y3 = -0.5*exp(-x);
>>
>> plot(x,y1, x,y2,'--', x,y3,'--')

3 . 19
HYPERBOLIC FUNCTIONS (2)

Resulting in

3 . 20
HYPERBOLIC FUNCTIONS
The hyperbolic functions appear as solutions to many civil engineering
problems such as
Water wave velocity
Catenary problem
Etc.

3 . 21
POLYNOMIALS
Has been a close friend since teen days
General form
2 N i
y(x) = a0 + a1 x + a2 x +. . . = ∑ ai x
i=0

Linear
y = mx + c

Quadratic
2
y = ax + bx + c

3 . 22
PLOTTING POLYNOMIALS

>> a1 = 1;
>> a2 = 0.1;
>> a3 = -0.5;
>> a4 = 0.5;
>>
>> x = linspace(-1,1,100);
>> y1 = a1*x + a2;
>> y2 = a1*x.^2 + a2*x + a3;
>> y3 = a1*x.^3 + a2*x.^2 + a3*x + a4
>> plot(x,y1, x,y2, x,y3)

'^' operator for raising to a power


'.' operator for element-by-element operation
x.^2 means, square all the elements in x 3 . 23
MATLAB EDITOR AND SCRIPT FILES
Tedious to keep on typing code into command window
Editor comes to the rescue - just like Pascal
Type in code, save in a .m le and press Run
3 . 24
SCRIPT FILES (1)

% Wipe the workspace, close all windows and clear the command window
clear; close all; clc;

%% Trigonometric functions

x = linspace(0, 4*pi, 100);


y1 = sin(x);
y2 = cos(x);

figure(1)
plot(x,y1,'b-', x,y2,'r--')

%% Exponential function

x = linspace(-1, 1, 100);
y = exp(x);

fi (2)

3 . 25
SCRIPT FILES (2)
Remember to put at the top of each script le
'clear' to clear all the variables
'close all' to close all the gure windows
'clc' to wipe the command window
Anything following a '%' is a comment
'%%' marks out sections - useful when debugging
gure( gNo) command opens up a new gure for plotting

3 . 26
MATLAB:
CONTROL FLOW AND FUNCTIONS

4.1
LOOPING
In MATLAB the general structure for a for loop is

for loopVar = some_vector


% repeated instructions
end

Executes for each element of some_vector


During each loop iteration, loopVar takes consecutive values of
some_vector

4.2
FOR LOOPS

some_vector = 1:4; Current value of loopVar =


for loopVar = some_vector 1
disp('Current value of loopVar ='
disp(loopVar) Current value of loopVar =
end 2

Current value of loopVar =


3

Current value of loopVar =


4

disp() is the MATLAB equivalent of writeln()

4.3
FOR LOOPS (2)
Now re-writing earlier examples using for loops

x = linspace(0, 4*pi, 100);


ind_arr = 1:length(x);

for i = ind_arr
y1(i) = sin(x(i));
y2(i) = cos(x(i));
end

figure(1)
plot(x,y1,'b-', x,y2,'r--')

Runs through each element of x, indexing using ind_arr


length(x) provides the number of elements vector x
y1 and y2 keeps on growing

4.4
FOR LOOPS (3)
What do you think happens below?

a(100) = 1;

Valid, but not recommended

4.5
FOR LOOPS (4)
A better alternative is to use zeros()

x = linspace(0, 4*pi, 100);


y = zeros(size(x));

for i = 1:length(x)
y = exp(x(i));
end

figure(1)
plot(x,y)

The size of the zero vector is speci ed using size(x)


We will come back to size() in Chapter 3
Also notice how the for loop is written
This is more colloquial MATLAB
While for loops are unavoidable sometimes, use them sparingly
4.6
DECISION MAKING
The syntax follows quite logically from Pascal

if condition1
% do something if condition1 is true
else if condition2
% do something if condition2 is true
else if condition3
% do something if condition3 is true
else
% Nothing above were true, so do what is here
end

4.7
DECISION MAKING: EXAMPLE
Checking whether a number is a multiple of 2, 3 or 4

a = 3;
if (mod(a,2) == 0)
disp('a was a multiple of 2');
if (mod(a,3) == 0)
disp('a was a multiple of 3');
if (mod(a,4) == 0)
disp('a was a multiple of 4');
else
disp('a was not a multiple of 2, 3, or 4');
end

mod(number1,number2) checks whether a reminder is left after


number1/number2
The operator '==' is used for equality

4.8
LOGICAL OPERATORS
In addition to '==', other operators are possible and summarised below

Operator Syntax
Equal to '=='
Not equal to '~='
Less than '<'
Less than or equal to '<='
Greater than '>'
Greater than or equal to '>='

For chaining the operators AND ('&&') and OR ('||') maybe used

4.9
LOGICAL OPERATORS: EXAMPLE
Checking whether a number is a multiple of 3 AND 5 at the same time

a = 15;
if ( (mod(a,3) == 0) && (mod(a,5) == 0) )
disp('a is a multiple of 3 and 5');
else
disp('a is NOT a multiple of 3 and 5');
end

Keep an eye on the paranthesis

4 . 10
COMBINING FOR AND IF
Let's plot the following complicated function
2
(x−2)
exp[− ]
2
−5 −4 8σ
y(x) = x ⋅ exp[−20x ] ⋅ 2

0.07 x ≤ 2
σ = {
0.09 x > 2

4 . 11
COMBINING FOR AND IF (2)

x = linspace(0, 4, 100);
y = zeros(size(x));

for i = 1:length(x)
if (x(i) >= 2)
sig = 0.07;
else
sig = 0.09;
end

y(i) = x(i)^(-5) * exp(-20*x(i)^(-4)) * ...


2^( exp(-(x(i) - 2)^2 / (8*sig^2) ) );
end

plot(x,y)

4 . 12
VECTORISATION
So far two approaches to compute vectors have been used - for loops
and whole vector functions
In MATLAB speak, the second method is called vectorisation
Logical conditions maybe combined with vectorisation to produce
succinct code
But rst, more indexing

4 . 13
MASK ARRAYS
Mask arrays are vectors containing ONLY true or false elements
If the length of a mask array and another vector are the same, mask
arrays can be used for indexing
When indexing, for each true index, the corresponding element in
the vector would be produced
For example, the following would be a normal way to produce the odd
indexed elements of v

v = [8, 4, 2, 1];
ind_arr = [1,3];
vodd = v(indarr)
8.0 2.0

Using mask arrays, this is achieved by

v = [8, 4, 2, 1];
mask_arr = [true, false, true, false];
vodd = v(maskarr)
8.0 2.0

4 . 14
RE-WRITING THE PREVIOUS EXAMPLE WITH MASK ARRAYS

x = linspace(0, 4, 100);
y = zeros(size(x));

mask1 = x <= 2;
sig1 = 0.07;

mask2 = x > 2;
sig2 = 0.09;

y(mask1) = x(mask1).^(-5) .* exp(-20*x(mask1).^(-4)) * ...


2.^( exp(-(x(mask1) - 2).^2 ./ (8*sig1^2) ) );

y(mask2) = x(mask2).^(-5) .* exp(-20*x(mask2).^(-4)) * ...


2.^( exp(-(x(mask2) - 2).^2 ./ (8*sig2^2) ) );

plot(x,y)

It is recommended that, whenever possible, use this instead of for loops

4 . 15
FUNCTIONS
Functions are usually written in script les
The function name and the script le name must be identical
The general form of a function in MATLAB is

function [output1, output2, ...] = fMyFunction(input1, input2, ...)

% do some awesome computations

output1 = % something
output2 = % something

end

Chain together as many output variables you want inside a []


Ensure that you assign to them inside the function
Similarly the inputs are written inside () after the function name
4 . 16
FUNCTIONS (2)
The previous function maybe written up as

function y = fExample2(x)

y = zeros(size(x));

mask1 = x <= 2;
sig1 = 0.07;

mask2 = x > 2;
sig2 = 0.09;

y(mask1) = x(mask1).^(-5) .* exp(-20*x(mask1).^(-4)) * ...


2.^( exp(-(x(mask1) - 2).^2 ./ (8*sig1^2) ) );

y(mask2) = x(mask2).^(-5) .* exp(-20*x(mask2).^(-4)) * ...


2.^( exp(-(x(mask2) - 2).^2 ./ (8*sig2^2) ) );

end

Once this is saved as fExample2.m, it maybe called as

x = linspace(0, 4, 100);
y = fExample2(x);
plot(x,y)

4 . 17
MANIPULATING FUNCTIONS

5.1
INTRODUCTION
For functions of the form, y = f (x), it is useful to be familiar with what
happens when they are shifted and scaled
This was covered in foundation pre-calculus

5.2
Y-AXIS SHIFTING
This is the easiest to visualise
For a shift of the form
y = f (x) + c

The graph shifts up (c > 0 ) or shifts down (c < 0 )

5.3
Y-AXIS SCALING

For a scaling of the form


y = cf (x)

The graph shrinks (c < 1 ) or expands (c > 1 )

5.4
X-AXIS SHIFTING

For a shift of the form


y = f (x + c)

The graph shifts to the left for (c > 0 ) and shifts to the right for (c < 0 )

5.5
X-AXIS SCALING

For a scaling of the form


y = f (cx)

The graph expands for (c < 1 ) and shrinks (c > 1 )

5.6
THE END

You might also like