Chapter-0 MATLAB Basics Final
Chapter-0 MATLAB Basics Final
Chapter Outline
7
1
2
5
3
4
MATLAB
• MATLAB stands for “MATrix LABoratory"
• The basic element in MATLAB is matrix.
• Even a single number (scalar) or a row/column vector is treated as a
special case of a matrix
Why this (MATLAB) matters?
• Most mathematical and engineering problems can be expressed in matrix form
(linear equations, data sets, transformations, differential equations).
• MATLAB has matrix operations built into the language, so we can perform complex
computations with very simple commands.
• In addition, many computing problems in chemical engineering can be solved more
readily using one of the existing software packages (example ASPEN). The need for a
more flexible environment arises when solving highly specialized problems. Many
companies have developed highly sophisticated models of their plant or parts of
their plant. Generally, these models can only be solved using custom designed
software; hence a programming environment is needed.
Advantages of Using MATLAB Draw Back of Using MATLAB
• Matrix-Oriented: MATLAB's basic element is the matrix • Slower Execution for Certain Tasks:
and , and most mathematical and engineering problems • Compared to low-level languages (e.g., C, Fortran),
can be expressed in matrix form (linear equations, data MATLAB can suffer from substantial loss in speed,
sets, transformations, differential equations).It has very especially in tasks that are not heavily matrix-based.
simple, high-level, intuitive Built-in functions for: • Limited Hardware Interaction:
• Linear algebra, calculus, differential equations • MATLAB is excellent for computation and visualization
• Data visualization and graphical analysis but provides little or no direct support for hardware
• Interactive Environment: Provides an interactive integration (e.g., sensors, controllers, real-time systems).
workspace where commands can be executed directly, • Other languages like C or Python (with libraries) are
more versatile for hardware access.
results visualized immediately, and programs tested
quickly. • Higher Cost
• Powerful Graphics: Comes with an extensive set of • MATLAB is a commercial software with significant
built-in plotting and visualization tools, making it easy licensing costs, which can be a limitation for students,
small companies, or open-source projects.
to generate 2D and 3D plots, graphs, and animations for
analysis. • Memory Intensive
• User-Friendly Programming: Offers a simple, high-level, • Handling very large datasets or simulations can lead to
high memory consumption compared to optimized
intuitive syntax. Unlike languages such as Fortran or lower-level implementations.
C/C++ or Python (without libraries like NumPy), MATLAB
does not require extra coding to handle matrix
operations — it’s native to the language, allowing
engineers to develop programs faster and with less
effort to handle linear algebra and numerical methods
computation.
Applications in Chemical Engineering:
• Reactor design: solving nonlinear energy & material balance equations
• Heat transfer: modeling temperature profiles
• Mass transfer: simulating distillation and absorption
• Process control & optimization: tuning and simulation
Chapter Outline
7
1
6
2
5
3
4
1
7
2
6
3
5
4
Help Window
Editor Window 6
Workspace
1 2
Command window
3
Command window: This is the main interface where we
Current Folder type commands, variables, and functions to be executed
immediately. It's also where the results of our commands
and error messages are displayed. Command History
>> prompt indicate readiness for input. 4
Entering Commands in the Command Window
Used for:
• Executing commands
• Opening other windows
• Running programs written by the user
• Managing the software
Help Window Workspace Window: This window displays(provides information about ) all
6 the variables we have created or loaded during a MATLAB session. It shows
Editor Window their names, sizes, values, and data types, allowing u to manage the data in
5 memory.
Workspace
2
3 1
Current Folder Command window
Command History
4
Entering the following Commands in the Command Window and notice the Workspace Window
Help Window
6
Editor Window
5
Workspace
2
3 1
Current Folder Command window
Current Folder Window: This window shows the contents of the current Command History
working directory (folder) that MATLAB is accessing. It allows you to 4
navigate the file system and open files like scripts and functions.
Help Window
6
Editor Window
5
Workspace
2
3 1
Current Folder Command window
Command History
4
Editor Window 6
Help Window
5
Workspace
2
3 1
Current Folder Command window
Command History
4
Help Window: This window provides access to MATLAB's
documentation, tutorials, and function references. It's essential for
looking up syntax, details, and examples for any function or tool
Editor Window 6
Help Window
5
Workspace
2
3 1
Current Folder Command window
Command History
4
Figure Window: This is a separate window that opens to display plots, graphs, and
images generated by our MATLAB code (e.g., from functions like plot, surf…).
7 Figure Window
1
7
2
6
3
5
These windows collectively form the integrated development environment (IDE) of MATLAB,
used for tasks from simple calculations to complex simulations and data visualization.
Chapter Outline
7
1
2
5
3
4
The declaration and proper use of variables and constants in MATLAB
- Subtraction ^ Power/exponentiation
/ Right division
Assignment = Equal
I Or
Perform a simple computations on command window.
Notes for working in the Command Window
Command Outcome
Comma (,)
Used to write several commands
in the same line
semicolon ( ; )
Used to suppress the output of
the command.
Up-arrow key Used to recall a previously typed
Down-arrow key command to the command
prompt.
% (percent) When typed at the beginning of
a line, the line is designated as a
comment. This has no effect on
the execution of the command.
… (ellipsis) If a command is too long to fit in
one line, it can be continued to
the next line by typing three
periods …
clc clears the Command Window
Ctrl+c Abort calculation
Exercise 1:
Write a program to convert a given temperature(45F) from F to C:
𝟓
𝑻𝑪 = 𝑻𝑭 − 𝟑𝟐 ∗
𝟗
Exercise 2:
Write a program to calculate the vapor pressure of water at 100oC according to Antoine equation:
𝐵
𝑃 = exp(𝐴 − )
𝐶+𝑇
Where T is temperature in Kelvin and A, B, and C are Antoine coefficients:
A=18.3036, B=3816.44, C= -46.13
Exercise 3:
For the following distillation column write a code to find the value
of stream B and the compositions of stream D?
Numerical Display Format
Command Display
>>format rat Fractional form
>>format short 4 decimal places
>>format short e 4 decimal places with exponent
>>format short g Short decimal places based on the significant number
>>format long 14 decimal places
>>format long e 14 decimal places with exponent
>>format long g Short decimal places based on the significant number
>>format bank 2 decimal places
Chapter Outline
7
1
2
5
3
4
Defining VECTORS and MATRICES
Explicit list
• Use square brackets [ ]
• Rows are separated by semicolons ;
• Elements within a row are separated by spaces or commas,
Example:
>>A = [10, 20, 30; 40, 50, 60; 70, 80, 90]; % Define matrix A
Accessing individual elements
>>element_1_1 = A(1, 1); % Accesses row-1 and column-1 of Matrix A, the value 10
>>element_2_3 = A(2, 3); % Accesses row-2 and column-3 of Matrix, A the value 60
Accessing multiple elements
>>selecte_elements = A([2,3], [2,3]); % Accesses a sub-matrix: [50, 60; 80, 90]
Accessing the dimensions of the matrix
>>length(A); % This function returns the length of the largest dimension of an array A. (which is 3 for this e.g)
>>size(A); % This function returns the corresponding dimensions of array A. (which is 3X3 for this e.g)
>>numel(A); % This function returns the total number of elements in an array A. (which is 3 for this e.g)
Chapter Outline
7
1
2
5
3
4
Example
Define the function 𝑓(𝑥) = 𝑥 in MATALB and calculate its value at 𝑓(5)
Why Use M-Files?
M-files are text files that contains MATLAB code (with .m extension) .
While we can run commands directly in the Command Window, M-files
are used for:
• Automation: Run many commands at once.
• Reproducibility: Save, share, and modify analyses.
• Organization: Structure long programs neatly.
• Debugging: Test and improve our code step-by-step.
• Reusability: Write functions to perform repeated tasks.
M-Files
M-files are text files that contains MATLAB code (with .m extension) .
Editor Window: This is where we create, modify, save and execute/debugs M-files (scripts and functions).
It's a text editor specifically designed for writing MATLAB code.
Editor Window 6
Help Window
5
Workspace
2
3 1
Current Folder Command window
Command History
4
Writing and Running Script M-Files
A script is like a notebook of MATLAB commands.
Example of a Script M-File
Create a Script M-file that calculate area of a circle of radius r=5cm.
Writing
% Save the script file name as “circle_area.m”
% This script calculates the area of a circle for radius of 5cm.
radius = 5; % radius in cm
area = pi * radius^2 % Computes the area in cm^2
Running
Call it from the Command Window >> circle_area or click on run in the editor
Writing and Running Function M-Files
• M-files contain programming, scripts, equations or data that are called upon
during an execution.
• A function file begins with the keyword function and has a specific structure:
Note:
• Function files must have the same name as the function (e.g file_name.m).
• Variables inside functions are local (they don’t appear in the base workspace)
Example
• Create a function M-file that calculate values of the function
Writing
function A = circleArea(r)
% Save the script file name as “CircleArea.m”
% CircleArea(r) returns the area of a circle of radius r
A = pi * r^2 % Computes the area in cm^2
end
Running
Note: Make sure your Current Folder (shown on MATLAB’s toolbar) is the same as where your file is saved
Call it from the Command Window:
>> CircleArea(5) % result will be 78.5398
Example of a Function M-File
Create a function M-file that calculate area of a circle of radius r.
Writing
function z = calculate_z(x,y)
% Save the script file name as “calculate_z.m”
% INPUT: x (scalar or matrix), y (scalar or matrix)
% OUTPUT: z (same size as x and y)
z = x.^2+y.^2 % Note the element-wise operator .^
end
Running
Note: Make sure your Current Folder (shown on MATLAB’s toolbar) is the same as where your file is saved
Call it from the Command Window:
>> calculate_z(3,4) % result will be 25
Difference Between Script and Function Files Summary
2
5
3
4
Basic Input and Output(I/O) Statements
Input Statements
• MATLAB input() function prompts the user for input.
Variable=input(‘format string’)
Example:
>>Pressure = input('Enter the reactor pressure (bar):');
>>Name = input('Enter your name: ', 's’); % The 's' is for string input
Example of a Function M-File
Create a function M-file that calculate area of a circle of radius r.
Writing
function A = CircleArea2(r)
% Save the script file name as “CircleArea2.m”
r=input('Enter radius: ‘); % This line promote the user to enter the desired value of the radius r
A = pi * r^2 % Computes the area in cm^2
end
Running
Note: Make sure your Current Folder (shown on MATLAB’s toolbar) is the same as where your file is saved
Call it from the Command Window or click on run in the editor
>> CircleArea2
Basic Input and Output(I/O) Statements
Output Statements
• fprintf() and disp() functions are the output statements in MATLAB.
fprintf offers formatted output.
fprintf('format string’, Variable)
How it works:
• The number is rounded to 3 decimal places
• The total output occupies at least 5 characters
• If the number needs more than 5 characters, it will use as many as needed
• Numbers are right-aligned within the field
Note:
Format specifiers are very useful for creating neatly aligned tables and formatted output in MATLAB.
Example of a Function M-File
Create a function M-file that calculate area of a circle of radius r.
Writing
function A = CircleArea3(r)
% Save the script file name as “CircleArea3.m”
r=input('Enter radius: ‘); % This line promote the user to enter the desired value of the radius r
A = pi * r^2 % Computes the area in cm^2
fprintf(‘The Area of the Circle is = %.2f cm^2\n’, A); % Displays the output in a formatted way
end
Running
Note: Make sure your Current Folder (shown on MATLAB’s toolbar) is the same as where your file is saved
Call it from the Command Window or click on run in the editor
>> CircleArea3
Example
1. Create a MATLAB program that can calculate the product of two
numbers.
2. Create a MATLAB program that can compute the average of three
input numbers.
Exercise 1*:
Write a program to convert a given temperature from K to oC:
Chapter Outline
7
1
6
2
5
3
4
• Concept: Execute different code blocks depending on whether conditions are true or false
• Analogy: Like a flowchart with decision points - "If this condition is met, do this; otherwise, do that"
Example
1. Create a MATLAB program that reads the reactor temperature from the user input and checks whether it
exceeds the safe operating limit of 400°C. If the temperature is above this threshold, the program should
display a warning message and indicate that emergency cooling is being activated.
2. Develop a MATLAB program that prompts the user to enter a concentration value in mol/L and checks
whether it is positive. If the entered concentration is zero or negative, the program should display an
error message and automatically replace the value with a default safe concentration of 0.1 mol/L.
3. Write a MATLAB program that prompts the user to enter a reaction conversion value and checks
whether the input lies within the valid range of 0 to 1. If the entered conversion is less than 0 or greater
than 1, the program should display an error message indicating that the value is outside the acceptable
range and then terminate the program.
Example
1. Create a MATLAB program that reads the reactor temperature from the user
input and checks whether it exceeds the safe operating limit of 400°C. If the
temperature is above this threshold, the program should display a warning
message and indicate that emergency cooling is being activated.
If condition1
statement1 % Code if condition1 is TRUE
elseif condition2
statement2 % Code if condition2 is TRUE
elseif condition3
statement3 % Code if condition3 is TRUE
.
.
.
else
statement i % Code if all conditions are FALSE
end
Example
1. Create a MATLAB program that accepts a temperature in °C and determines the
corresponding phase of water based on numerical thresholds: solid for temperatures ≤
0°C, liquid for temperatures between 0°C and 100°C, and gas for temperatures ≥
100°C. The program should then compute the specific enthalpy using the appropriate
phase-based correlations:
• Solid (Ice):
• Liquid Water:
• Steam:
Finally, the program must display both the identified phase and the calculated specific
enthalpy.
2. Create a MATLAB program that evaluates a chemical process using the following
performance metrics: yield = 0.85, purity = 0.95, and cost = 120. The program should
check whether the process satisfies all optimization criteria—yield greater than 0.8,
purity greater than 0.9, and cost below 150. Based on these values, the program must
determine if the process is ready for scale-up, if only the cost requires further
optimization, or if the process needs significant overall improvement.
Example
Create a MATLAB program that accepts a temperature (°C) as input and determines
the phase of water—solid, liquid, or gas—based on the given temperature. The
program should then calculate the corresponding specific enthalpy using appropriate
phase-based correlations and display the computed enthalpy value.
% Determine water phase based on temperature
T = input('Enter temperature (C): ');
if T <= 0
disp('Phase: Solid (Ice)');
enthalpy = 2.09 * T; % Ice enthalpy approximation
elseif T < 100
disp('Phase: Liquid');
enthalpy = 4.18 * T; % Liquid water enthalpy
else
disp('Phase: Gas (Steam)');
enthalpy = 2257 + 2.01 * T; % Steam enthalpy
end
fprintf('Specific enthalpy: %.2f kJ/kg\n', enthalpy);
Example
Create a MATLAB program that evaluates a chemical process using the following
performance metrics: yield = 0.85, purity = 0.95, and cost = 120. The program should check
whether the process satisfies all optimization criteria—yield greater than 0.8, purity greater
than 0.9, and cost below 150. Based on these values, the program must determine if the
process is ready for scale-up, if only the cost requires further optimization, or if the process
needs significant overall improvement.
• Final: Final value - loop stops when index exceeds this value
% Count by 2s
for i = 2:2:10
fprintf('i = %d\n', i);
end
% Count backwards
for i = 5:-1:1
fprintf('Countdown: %d\n', i);
end
Example
Write a MATLAB program that calculates the sum of all even numbers from 0 to
100. The program should use a loop to iterate through the numbers in steps of 2,
accumulate the sum, and then display the final result.
% Calculate the sum of even numbers from 0 to 100
sum_even = 0; % Initialize sum accumulator
for i = 0:2:100 % Start at 0, increment by 2, up to 100
sum_even = sum_even + i; % Add current even number to sum
end
fprintf('Sum of even numbers is %d.\n', sum_even);
Example
Zero-Order Reaction Given: Ca0 = 15 gmol/L, k = 0.0567 gmol/L-sec.
Compute concentration from t=0 sec to t=60 sec every 10 sec.
Plot Time vs. Concentration.
% Using a for loop
Ca0 = 15;
k = 0.0567;
time = 0:10:60;
concentration = zeros(size(time)); % Pre-allocate for efficiency
for i = 1:length(time)
t = time(i);
concentration(i) = Ca0 - k * t; % Zero-order kinetics: Ca = Ca0 - k*t
end
% Count by 2s
i = 2; % Initialize counter
while i <= 10
fprintf('Counter value: %d\n', i);
i = i + 2; % Increment by 2
end
% Count backwards
i = 5; % Initialize counter at 5
while i >= 1
fprintf('Countdown: %d\n’, i);
i = i - 1; % Decrement by 1
end
% Calculate the sum of even numbers from 0 to 100
sum_even = 0;
i = 0;
while i <= 100
sum_even = sum_even + i;
i = i + 2; % Increment by 2 to get next even number
end
fprintf('Sum of even numbers is %d.\n', sum_even);
Example
Zero-Order Reaction Given: Ca0 = 15 gmol/L, k = 0.0567 gmol/L-sec.
Compute concentration from t=0 sec to t=60 sec every 10 sec.
Plot Time vs. Concentration.
% Using a while loop
Ca0 = 15;
k = 0.0567;
time = 0:10:60;
concentration = zeros(size(time)); % Pre-allocate for efficiency
% Increment counter
i = i + 1;
end
2
5
3
4
Example
Example
Plotting Benzene-Toluene equilibrium curve
X Y
0.0 0.000
0.1 0.211
0.2 0.378
0.3 0.512
0.4 0.623
0.5 0.714
0.6 0.791
0.7 0.856
0.8 0.911
0.9 0.959
1.0 1.000
Color Codes
Options for Enhancing Plots Symbol Color RGB Example
Marker Styles Line Styles r Red 'Color',''
o Circle * star
Symbol Style g Green 'Color',’g'
d Diamond < Triangle pointing left
h Hexagram > Triangle pointing right - Solid line b Blue 'Color','b'
p Pentagram ^ Triangle pointing up
-- Dashed line
+ Plus v Triangle pointing down c Cyan [0 1 1]
. Point x Cross mark : Dotted line
s Square -o Data points connected by a line
m Magenta [1 0 1]
-. Dash-dot line y Yellow [1 1 0]
k Black [0 0 0]
plot(x, y, 'r--', 'LineWidth', 2); % Red dashed line, thicker
w White [1 1 1]
title(‘Title of the plot’); % Places a title on the upper part of the graph
xlabel(‘X-axis Label’); % Provides a label for the x-axis
ylabel(‘Y-axis Label’); %Provides a label for the y-axis
legend(‘Legend of the graph’); % Places a legend on the upper right part of the graph
gtext() % Prints text in the graph (location provided through the mouse)
grid on;
• Try
Alternative way of
doing it
The simplest way to graph a function is to use the command ezplot
(easy plot).
Example
Graph the function y=x²+x+1,
>>ezplot('x^2+x+1')
Three-Dimensional Plots
>>plot3(x,y,z) will produce a perspective plot of
the piecewise linear curve in 3-space
t = 0:pi/50:10*pi; x = sin(t);
y = cos(t);
z = t;
plot3(x, y, z);
title('3D Spiral');
xlabel('X');
ylabel('Y');
zlabel('Z'); grid on;