Professional Documents
Culture Documents
CHEN309 Lec2
CHEN309 Lec2
CHEN309 Lec2
ENGINEERS
April 2021
Learning Outcomes
On most systems, Octave is started with the shell command ‘octave’. This
starts the graphical user interface. The central window in the GUI is the
Octave command-line interface.
If you get into trouble, you can usually interrupt Octave by typing Control-
C (written C-c for short).
Logical/conditional operations
String
Class Syntax Description Examples
Name
char char (X) Create a string array char ([97, 98, 99], "",
char (X, ...) from one or more {"98", "99", 100}, "str1",
char (S1, S2, ...) numeric matrices, ["ha", "lf"])
char (CELL_ARRAY) character matrices, or ⇒ ["abc "
cell arrays. " "
"98 "
"99 "
"d "
"str1"
"half"]
Numeric integers
Class Name Syntax Description Examples
⇒ integer = 0 1 0 1
Floating point numbers
Class Syntax Description Examples
Name
single single(X) Convert X to single sngl = single (rand (2, 2))
precision type ⇒ sngl =
0.37569 0.92982
Most of the functions in 0.11962 0.50876
Octave accept single class (sngl)
precision values and ⇒ single
return single precision
answers.
double double(X) Convert X to double
precision type.
>> y = 2*x – 5
>> y = y + 1
Note that the symbol “=” , called assignment operator, is different from the
usual algebraic equality sign.
Examples of Basic Arithmetic Operations
Mathematical expression/equation Octave expression/equation
The comparison (relational) operators return 1 for true and 0 for false.
Note the following built-in functions: lt(a,b), gt(a,b), le(a,b), ge(a,b), eq(a,b),
ne(a,b)
Logical Operators
Logical operators are:
Operator Meaning
& AND
| OR
~ NOT
X Y X AND Y X OR Y X XOR Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Plotting
2-D Line Plots
Linear : plot(xvect,yvect)
Logarithmic Plot: loglog(xvect,yvect)
SemiLogarithmic Plots: semilogx(xvect,yvect)
semilogy(xvect,yvect)
Plots with special graphics
Vertical bar plot: bar(xvect,yvect)
Horizontal bar plot: barh(xvect,yvect)
Stairs plot: stairs(xvect,yvect)
Stem plot: stem(xvect,yvect)
Pie chart: pie(x)
Histogram: hist(y)
Scatter: scatter(xvect, yvect)
Plotting
3-D Plots
3-D line plot plot3(X,Y,Z)
Creating grid points meshgrid(X,Y)
Mesh plot mesh(X,Y,Z)
Surface plot surf(X,Y,Z)
Contour plot Contour(X,Y,Z)
Surface + Contour plot surfc(X,Y,Z)
Plotting
For example, try
>> x = 0:1:100;
>> y = 2.*x.^2;
>> subplot(2,2,1); plot(x,y);
>> subplot(2,2,2); loglog(x,y);
>> subplot(2,2,3); semilogx(x,y);
>> subplot(2,2,4); semilogy(x,y)
Plotting
For example, try
>> t = linspace(0,10*pi);
>> plot3(sin(t),cos(t),t);
>> xlabel(‘sin(t)’);ylabel(‘cos(t)’);zlabel(‘t’)
Also try
>>[X,Y] = meshgrid(-2:0.1:2, -2:0.1:2);
>> Z = X.ˆ2 - Y.ˆ2;
>> figure (1); mesh(X,Y,Z);
>> figure (2); contour(X,Y,Z);
>> figure (3); surf(X,Y,Z);
>> figure (4); surfc(X,Y,Z)
Plotting
Axis labels and a title can be added using the commands:
>> title(‘Simple Plot’);
>> xlabel(‘x’);
>> ylabel(‘Sine and Cosine’);
Octave tries to choose sensible extreme values for the axes.
These can be overwritten using the command axis(v) where
v=[Xmin Xmax Ymin Ymax]
Most plot properties can be edited from the plot window by
clicking on the little diagonal arrow on the tool bar then clicking
on any feature of the plot you’d like to edit (axis, curve thickness
color…)
Plot
Example: Sombrero plot
tx = ty = linspace (-8, 8, 41)';
[xx, yy] = meshgrid (tx, ty);
r = sqrt (xx .^ 2 + yy .^ 2) + eps; tz = sin (r) ./ r;
mesh (tx, ty, tz);
xlabel ("tx"); ylabel ("ty"); zlabel ("tz");
title ("3-D Sombrero plot");
Display Formatting Commands
Style Result Example
short (default) Short, fixed-decimal format with 4 digits after the decimal point. 3.1416
long Long, fixed-decimal format with 16 significant figures 3.141592653589793
shorte or shortE Short scientific notation with 4 digits after the decimal point. 3.1416e+00 or 3.1416E+00
longe or longE Long scientific notation with 15 digits after the decimal point 3.141592653589793e+00
for double values, and 7 digits after the decimal point for single values. 3.141592653589793E+00
shortG short or shortE, whichever is more compact. 3.1416
longG long or longE, whichever is more compact. 3.14159265358979
shortEng Short engineering notation (exponent is a multiple of 3) with 4 digits 3.1416e+000
after the decimal point.
longEng Long engineering notation (exponent is a multiple of 3) with 15 3.14159265358979e+000
significant digits.
+ Positive/Negative format with +, -, and blank characters displayed for +
positive, negative, and zero elements.
bank Currency format with 2 digits after the decimal point. 3.14
hex Hexadecimal representation of a binary double-precision number. 400921fb54442d18
rat Ratio of small integers. 355/113
bit Print the bit representation of numbers as stored in memory. Always print 010000000000100100100001111
the most significant bits first. 110110101010001000100001011
0100011000
Example: Energy stored in a spring
The force required to compress a linear spring is given by the equation
𝐹 = 𝑘𝑥
Where F is force in N and k is the spring constant in N/m. The potential energy E (in J)
stored in the compressed spring is given by the equation
1
𝐸 = 𝑘𝑥 2
2
The following information is available for four springs
M-Files
Script Function
files files
Script File
A script file is a list of Octave commands, called a program, that is saved in a
file.
When the script file is executed (run), Octave executes the commands.
Syntax
Block Comments
Entire blocks of code can be commented by enclosing the code
between matching ‘#{’ and ‘#}’ or ‘%{’ and ‘%}’ markers.
fprint Statements
Opening/closing files for reading and/or writing
Syntax Explanation
fid = fopen (name) mode
fid = fopen (name, mode) ‘r’: open file for reading.
fid = fopen (name, mode, arch) ‘w’: open file for writing. The previous contents are discarded.
[fid, msg] = fopen (…) ‘a’: Open or create a file for writing at the end of the file.
fid_list = fopen ("all") ‘r+’: Open an existing file for reading and writing.
[file, mode, arch] = fopen (fid) ‘w+’: Open a file for reading or writing. The previous contents
are discarded.
‘a+’: Open or create a file for reading or writing at the end of
the file.
fclose (fid) • Close the file specified by the file descriptor fid.
fclose ("all") If successful, fclose returns 0, otherwise, it returns -1.
status = fclose ("all") • The second form of the fclose call closes all open files except
stdin, stdout, stderr, and any FIDs associated with gnuplot.
Examples
Practice Problem
Write a user defined function file that converts temperature given in oF to
oC, K and R
clear all
clc
CGPA = input(‘Enter Student CGPA >> ’)
Solution
function sumx = myfun(x,n)
Calculate the molar flow rates of streams D1, D2, B1 and B2.
Example
clear all
clc
sol = dsolve([ode1;ode2;ode3])
sol{1,1)
sol{1.2}
sol{1.3}
Example: Irreversible Reactions in Series
clear all
clc
pkg load symbolic
syms t k1 k2 cA(t) cR(t) cS(t) cA0 cRo cSo
ode1 = diff(cA(t),t) + k1*cA(t);
ode2 = diff(cR(t),t) - k1*cA(t) + k2*cR(t);
ode3 = diff(cS(t),t) - k2*cR(t);
sol = dsolve([ode1;ode2;ode3], ...
cA(0)==cA0,cR(0)==cRo, cS(0)==cSo)
sol{1,1}
sol{1,2}
sol{1,3}
Numerical Solutions: Nonlinear Equations
𝑔1 𝑥, 𝑦 = 2𝑥 + 𝑦 − 𝑥 + 𝑦 − 3 = 0 syms x y
5
𝑔2 𝑥, 𝑦 = 4 − 𝑦 − =0 g1 = 2*x + y - sqrt(x+y) - 3;
𝑥+𝑦 g2 = 4 -y - 5/(x+y);
sol = solve(g1,g2,x,y)
x1 = double(sol{1,1}.x)
y1 = double(sol{1,1}.y)
x2 = double(sol{1,2}.x)
y2 = double(sol{1,2}.y)
Example: Non-linear equations
𝑑𝑦2
= −0.8𝑦2 + 0.3𝑦1 𝑦2
𝑑𝑡
𝑑𝐶𝑅
= −𝑘1 𝐶𝑅 + 𝑘3 𝐶𝑆 ; 𝐶𝑅 0 = 1.5
𝑑𝑡
𝑑𝐶𝑆
= 𝑘1 𝐶𝑅 − 𝑘3 𝐶𝑆 − 𝑘2 𝐶𝑆 ; 𝐶𝑆 0 = 0
𝑑𝑡
𝑑𝐶𝑄
= 𝑘2 𝐶𝑆 ; 𝐶𝑄 0 = 0
𝑑𝑡
Example 2: ODE Solution
clear all function dcdt = odefun(t,c)
clc CR = c(1);
CS = c(2);
tspan = [0 25]; CG = c(3);
y0 = [1.5 0 0];
[t y] = ode45(@odefun, tspan, y0) k1 = 0.4;
k2 = 1;
%Plot Results k3 = 0.3;
plot(t,y(:,1),'r',t,y(:,2),'k',t,y(:,3),'b')
xlabel('time, min') dcdt=[-k1*CR + k3*CS
k1*CR - k3*CS-k2*CS
ylabel (' C_R, C_S and C_G')
k2*CS];
legend ( 'C_R', 'C_S', 'C_G')
Example 2: ODE Solution
Polynomial Fitting
Return the coefficients of a ❑ Evaluate the polynomial p at the
polynomial p(x) of degree n that specified values of x.
• y = polyval (p, x)
minimizes the least-squares-error • y = polyval (p, x, [], mu)
of the fit to the points [x, y]. • [y, dy] = polyval (p, x, s)
p = polyfit (x, y, n) • [y, dy] = polyval (p, x, s, mu)
∞ −𝑥 2
0 𝑒 ln 𝑥 2 𝑑𝑥
3 1
0 𝑥 𝑠𝑖𝑛
𝑥
1 − 𝑥 𝑑𝑥
% Calculate volume
V = FA0*trapz(X, -1./rA)