0% found this document useful (0 votes)
25 views41 pages

@ Matlab

The document discusses MATLAB interfaces, M-files, and matrices. It describes the MATLAB workspace, command window, current directory, and command history. It explains how to create and save M-files with the ".m" extension and include comments. It also defines what a matrix is in MATLAB and how they can be built using brackets with rows separated by semicolons.

Uploaded by

Himanshu Patel
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)
25 views41 pages

@ Matlab

The document discusses MATLAB interfaces, M-files, and matrices. It describes the MATLAB workspace, command window, current directory, and command history. It explains how to create and save M-files with the ".m" extension and include comments. It also defines what a matrix is in MATLAB and how they can be built using brackets with rows separated by semicolons.

Uploaded by

Himanshu Patel
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/ 41

WO709-COMPUTATIONAL HYDRODYNAMICS LAB

PROGRAMMING USING MATLAB

Dr. DEBABRATA KARMAKAR


ASSOCIATE PROFESSOR
DEPARTMENT OF WATER RESOURCES & OCEAN ENGINEERING

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 1
MATLAB INTERFACES

Workspace

Command Window

Command History

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 2
MATLAB INTERFACES CONTD….

❑ Command Window
❑ type commands

❑ Current Directory
❑ View folders and m-
files

❑ Workspace
❑ View program
variables
❑ Double click on a
variable to see it in
the Array Editor

❑ Command History
– view past commands
– save a whole session
using diary
Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 3
USE OF M-FILE

Click to create
a new M-File

• Extension “.m”
• A text file containing script or function or program to run
Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 4
USE OF M-FILE CONTD….
Save file as Prog.m

If you include “;” at the


end of each statement,
result will not be shown
immediately

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 5
WHAT IS MATLAB?
❑ Abbreviation of MATrix LABoratory
❑ Is a high-performance language for technical computing
❑ It integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar
mathematical notation.

USAGE OF MATLAB

❖ Math and computation


❖ Algorithm development
❖ Data acquisition
❖ Modeling, simulation, and prototyping
❖ Data analysis, exploration, and visualization
❖ Scientific and engineering graphics
❖ Application development including graphical user interface building

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 6
MATLAB SYSTEM

MATLAB

Simulink
Applications Develop Tools

Stateflow
Toolboxes

Module Libraries
DATA Data-Accessing Tools

Generating-Codes Tools C

Third parties modules

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 7
BUILDUP OF MATLAB
❑ Development Environment
MATLAB desktop and Command Window, a command history, an editor and debugger, and
browsers for viewing help, the workspace, files, and the search path.

❑ The MATLAB Mathematical Function Library


A vast collection of computational algorithms ranging from elementary functions to more
sophisticated functions

❑ The MATLAB Language


A high-level matrix/array language with control flow statements, functions, data structures,
input/output, and object-oriented programming features

❑ Graphics
➢ Display vectors and matrices as graphs
➢ two-dimensional and three-dimensional data visualization
➢ image processing
➢ animation and presentation graphics

❑ The MATLAB Application Program Interface (API)


Interchange the C/Fortran codes with Matlab codes

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 8
MATLAB SPECIAL VARIABLES

ans Default variable name for results


pi Value of 
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real number
realmax The largest usable positive real number

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 9
MATLAB MATH & ASSIGNMENT OPERATORS
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a

NOTE: 56/8 = 8\56

- (unary) + (unary)
Addition + a+b
Subtraction - a-b
Assignment = a=b (assign b to a)

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 10
OTHER MATLAB SYMBOLS

>> prompt
... continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 11
MATLAB RELATIONAL OPERATORS

❑ MATLAB supports six relational operators.

Less Than <


Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 12
MATLAB LOGICAL OPERATORS

❑ MATLAB supports three logical operators.

not ~ % highest precedence


and & % equal precedence with or
or | % equal precedence with and

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 13
What does Matlab code look like?

Another simple example:


EVERYTHING IN MATLAB
t = 0:pi/100:2*pi;
y = sin(t); IS A MATRIX !
plot(t,y)

creates 1 x 200 Matrix

Argument and result: 1 x 200 Matrix

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 14
MATRICES

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 15
MATRICES CONTD….

❑ Rows and columns are always numbered starting at 1

❑ MATLAB matrices are of various types to hold different


kinds of data (usually floats or integers)

❑ A single number is really a 1 x 1 matrix in MATLAB!

❑ MATLAB variables are not given a type, and do not need


to be declared

❑ Any matrix can be assigned to any variable

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 16
MATRICES CONTD….

Building matrices with [ ]:

A = [2 7 4] 2 7 4

2
A = [2; 7; 4]
7
4

2 7 4
A = [2 7 4; 3 8 9]
3 8 9

2 7 4 2 7 4
B = [ AA ] 3 8 9 3 8 9
Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 17
MATRICES CONTD….

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 18
VARIABLES

❑ No need for types. i.e., int a;


double b;
float c;

❑ All variables are created with double precision unless specified and they are
matrices.
Example:
>>x=5;
>>x1=2;

❑ After these statements, the variables are 1x1 matrices with double precision

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 19
ARRAY, MATRIX

• a vector x = [1 2 5 1]

x =
1 2 5 1

• a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x =
1 2 3
5 1 4
3 2 -1

• transpose y = x’ y =
1 5 3
2 1 2
3 4 -1

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 20
LONG ARRAY, MATRIX

• t =1:10

t =
1 2 3 4 5 6 7 8 9 10
• k =2:-0.5:-1

k =
2 1.5 1 0.5 0 -0.5 -1

• B = [1:4; 5:8]

B =
1 2 3 4
5 6 7 8

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 21
GENERATING VECTOR FROM FUNCTIONS

• zeros(M,N) MxN matrix of zeros x = zeros(1,3)


x =
0 0 0

• ones(M,N) MxN matrix of ones x = ones(1,3)


x =
1 1 1

• rand(M,N) MxN matrix of uniformly


distributed random x = rand(1,3)
numbers on (0,1) x =
0.9501 0.2311 0.6068

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 22
MATRIX INDEX
❑ The matrix indices begin from 1 (not 0 (as in C))
❑ The matrix indices must be positive integer
Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)
Error: ??? Index exceeds matrix dimensions.

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 23
CONCATENTION OF MATRICES
In formal language theory and computer programming, string concatenation is the
operation of joining character strings end-to-end.

• x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y] 1 2 4 5

B = [x ; y] 12
45

C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 24
MATRIX OPERATION
Given A and B:

Addition Subtraction Product Transpose

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 25
USE OF “.” – “ELEMENT” OPERATION
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
USE OF “.” – “ELEMENT” OPERATION
3 2 -1

x = A(1,:) y = A(3 ,:) b = x .* y c=x./y d = x .^2

x= y= b= c= d=
1 2 3 3 2 -1 3 4 -3 0.33 1.0 -3 1 4 9

K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 26
CONTROL STRUCTURES

Some Dummy Examples


• If Statement Syntax
if ((a>3) & (b==5))
if (Condition_1) Some Matlab Commands;
Matlab Commands end
elseif (Condition_2)
Matlab Commands if (a<3)
elseif (Condition_3) Some Matlab Commands;
elseif (b~=5)
Matlab Commands
Some Matlab Commands;
else end
Matlab Commands
end if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 27
CONTROL STRUCTURES CONTD….

Some Dummy Examples


for i=1:100
• For loop syntax Some Matlab Commands;
end

for j=1:3:200
for i=Index_Array Some Matlab Commands;
end
Matlab
for m=13:-0.2:-21
Commands Some Matlab Commands;
end
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 28
CONTROL STRUCTURES CONTD….

• While Loop
Syntax
Dummy Example

while ((a>3) & (b==5))


while (condition) Some Matlab Commands;
end
Matlab
Commands
end

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 29
C++ VS MATLAB

int j; for i = 1:2:N


. for J = 1:N
for (j=1;j<23;j=j+2)
A(I,J) =(I+J-1);
{
end
A[4][j]=3*j;
} end

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 30
C++ VS MATLAB CONTD….

int j;
while N> 0,
E = E + F;
while (j<28)
F = A*F/N;
{
N = N + 1;
…….;
end
}

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 31
C++ VS MATLAB CONTD….

If (I = = j) if i == j
{ A[i][j]=2; A(i,j) = 2;
} elseif abs(i-j) ~= 1
else if (abs(i-j)!=1) A(i,j) = -1;
{ else
…….; A(i,j) = 0;
} end

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 32
PLOT
PLOT Linear plot. Example

• PLOT(X,Y) plots vector Y x = [-3 -2 -1 0 1 2 3];


versus vector X y1 = (x.^2) -1;
plot(x, y1,'bo-.');
• PLOT(Y) plots the columns
of Y versus their index

• PLOT(X,Y,S) with plot


symbols and colors

• See also SEMILOGX,


SEMILOGY, TITLE,
XLABEL, YLABEL, AXIS,
AXES, HOLD, COLORDEF,
LEGEND, SUBPLOT...

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 33
PLOT PROPERTIES
Example
XLABEL X-axis label.
...
• XLABEL('text') adds text xlabel('x values');
beside the X-axis on the ylabel('y values');
current axis.

YLABEL Y-axis label.


• YLABEL('text') adds text
beside the Y-axis on the
current axis.

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 34
HOLD
Example
...
HOLD Hold current graph. hold on;
y2 = x + 2;
• HOLD ON holds the current plot(x, y2, 'g+:');
plot and all axis properties
so that subsequent graphing
commands add to the
existing graph.
• HOLD OFF returns to the
default mode
• HOLD, by itself, toggles the
hold state.

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 35
SUBPLOT
SUBPLOT Create axes in tiled
positions.
• SUBPLOT(m,n,p), or
SUBPLOT(mnp), breaks the Figure
window into an m-by-n matrix of
small axes
Example
x = [-3 -2 -1 0 1 2 3];
y1 = (x.^2) -1;
% Plot y1 on the top
subplot(2,1,1);
plot(x, y1,'bo-.');
xlabel('x values');
ylabel('y values');
% Plot y2 on the bottom
subplot(2,1,2);
y2 = x + 2;
plot(x, y2, 'g+:');
Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 36
FIGURE
FIGURE Create figure window.
• FIGURE, by itself, creates a
new figure window, and returns
its handle.

Example
x = [-3 -2 -1 0 1 2 3];
y1 = (x.^2) -1;
% Plot y1 in the 1st Figure
plot(x, y1,'bo-.');
xlabel('x values');
ylabel('y values');
% Plot y2 in the 2nd Figure
figure
y2 = x + 2;
plot(x, y2, 'g+:');

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 37
SURFACE PLOT
x = 0:0.1:2;
y = 0:0.1:2;
[xx, yy] = meshgrid(x,y);
zz=sin(xx.^2+yy.^2);
surf(xx,yy,zz)
xlabel('X axes')
ylabel('Y axes')

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 38
3D SURFACE PLOT
contour-colorbar-plot3-waterfall-contour3-mesh-surf

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 39
ROOTS OF TRANCENDENTAL EQUATION
NEWTON-RAPHSON METHOD

% Newton Raphson Method


clear all
close all
clc
% Change here for different functions
f=@(x) cos(x)-3*x+1
% Derivative of the function
df=@(x) -sin(x)-3
% Initial Guess
x=0.3;
for i=1:1:100 x=0.3;
x1=x-(f(x)/df(x)); error(5)=0;
x=x1; for i=1:1:5
end x1=x-(f(x)/df(x));
sol=x; x=x1;
fprintf('Approximate Root %.15f',sol) error(i)=x1-sol;
end
plot(error)
xlabel('Number of iterations')
ylabel('Error')
title('Error Vs. Number of iterations')

Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 40
Thank you
Department of Water Resources & Ocean Engineering, NITK Surathkal Dr. Debabrata Karmakar 41

You might also like