0% found this document useful (0 votes)
3 views103 pages

Chapter-0 MATLAB Basics Final

The document provides an overview of MATLAB, emphasizing its matrix-oriented nature and applications in mathematical and engineering problems. It outlines the advantages and drawbacks of using MATLAB, including its user-friendly programming environment and powerful graphics capabilities, while also noting limitations such as slower execution speed and high costs. Additionally, it covers the importance of variable declaration, matrix operations, and the use of M-files for automation and organization in coding.

Uploaded by

abr6
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)
3 views103 pages

Chapter-0 MATLAB Basics Final

The document provides an overview of MATLAB, emphasizing its matrix-oriented nature and applications in mathematical and engineering problems. It outlines the advantages and drawbacks of using MATLAB, including its user-friendly programming environment and powerful graphics capabilities, while also noting limitations such as slower execution speed and high costs. Additionally, it covers the importance of variable declaration, matrix operations, and the use of M-files for automation and organization in coding.

Uploaded by

abr6
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

MATLAB Basics

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

Command History Window: This keeps a record of all the commands we


have executed in the Command Window, allowing us to recall, reuse, or modify
previous commands without retyping them.
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
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

Why this matters?


• In chemical engineering, we deal with governing equations like heat and material balances, reaction kinetics,
and transport phenomena. To solve these numerically in MATLAB, we must first define the parameters.
• Clearly declaring these allows us to translate complex real-world models (like a non-isothermal reactor) into
computational code. Without them, we can't perform any analysis, optimization, or process control.

Concept Chemical Engineering Example MATLAB Application


Variables Concentration (C), Temperature (T), Time Variables are used to hold values that will
(t), Reactor Volume (V) change throughout the calculation (e.g., C
will change with t).
Constants Universal Gas Constant (R), Activation Constants are used for values that do not
Energy (Ea), Heat of Reaction (ΔH), Rate change during a specific calculation or
Constant (k) simulation.

>>Cons = 5.67; %Constants: Reaction rate constant


>>Var = (Mass * Cp) / Volume; %Variables: Calculated energy density
Best Practices for MATLAB Variables and Constants Declaration

Feature Rules for declaring constant and variable names Example


Descriptive • Makes code self-documenting and prevents mixing up parameters flow_rate_A, temp_reactor,
Naming (e.g., mass flow rate of A vs. mass flow rate of B). volume_tank
• Must be composed of letters, numbers, and/or underscores. Must
always start with a letter
• Use an underscore if a two_word name cannot be avoided.
• Existing keywords cannot be used as variable names: (ans, pi, eps, j)
Case • MATLAB is case sensitive. Using Temp and temp will create two T≠t (Temperature vs. Time)
Sensitivity separate variables. Poor naming is a major source of bugs.
Defining • Constants are typically defined at the beginning of a script to ensure R_GAS = 8.314; (Universal
Constants they are consistent throughout the entire model. Gas Constant, in J/mol⋅K)
Matrix • MATLAB is optimized for matrices. All variables are technically Defining a set of
Operations matrices. Understanding this is key to solving systems of equations concentrations as a vector: C =
(like mass balances) efficiently. [C_A; C_B; C_C]

Example: Command Window


>>Cons=constant value
>>Var=equation result or value
Commands for Managing Variables

Commands For Managing Variables


Command Outcome
clc Clears the Command Window.
clear Removes all variables from the memory/workspace.
clear x y z Removes only variables x, y, and z from the memory.
who Displays a list of the variables currently in the memory.
whos Displays a list of the variables currently in the memory and
their sizes together with information about their bytes and
class
Operators
Operator Symbol Meaning Symbol Meaning

Arithmetic + Addition \ Left division

- Subtraction ^ Power/exponentiation

* Multiplication () Evaluation rule specifier

/ Right division

Assignment = Equal

Relational > Greater than <= Less than or equal to

>= Greater than or equal to == Equal to

< Less than ~= Not equal to

Logical & And II Or(with shortcut)

&& And(with shortcut) ~ Not

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 = [1, 2, 3; 4, 5, 6; 7, 8, 9]; % A 3x3 matrix


>>B = [10 20 30]; % A 1x3 row vector
>>C = [40; 50; 60; % A 3x1 column vector
Defining VECTORS and MATRICES
The Colon Operator
• Creates a sequence of numbers.
• Syntax: Matrix_Name= start:interval:end
Example:

>>D = [3.5:-0.5:1]; % Result: [3.5, 3.0, 2.5, 2.0, 1.5, 1.0]


>>E = [1:5]; % If interval is omitted, it defaults to 1. Result: [1, 2, 3, 4, 5]
Other Useful Matrix Functions

zeros(N) : %Creates an N-by-N matrix of zeros.


zeros(N,M) or zeros([N,M]): % Creates an N-by-M matrix of zeros.
ones(N): %Creates an N-by-N matrix of ones.
ones(N,M) :%Creates an N-by-M matrix of ones.
eye(N): %Creates an N-by-N identity matrix.
Accessing Matrix Elements
Use parentheses( )with row and column indices. Indexing starts at 1
10 20 30
𝐴 = 40 50 60
70 80 90

>>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:

function [output1,output2,…]=file_name(input1, input2)


the dependent variable name of the m-file the independent variables

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

for several values of .


Example of a Function M-File
Create a function M-file that calculate area of a circle of radius r.

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

Feature Script Function


Workspace Base workspace Local (function) workspace
Input/Output None Defined inputs/outputs
Reusability Limited High
Naming Any Must match the function name
Typical Use Quick tasks, plotting, sequential operations Modular programs, repeated calculations
Chapter Outline
7
1

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)

Any string or character Variable


Equation result
Other information
+
Data type format

• disp() is simpler, good for displaying text or variable values directly.


disp('format string’)
Example
>>name = 'Alice'; age = 30; fprintf('Name: %s, Age: %d\n', name, age);
>>fprintf(‘The pressure of the reactor is %5.3f. \n’, Pressure)

% marker, Start of format specifier


5 Minimum No. of field width (total characters including decimal point & digits)
3 No. precision (3 digits after decimal point)
f,d,e,g,c or s data type format
\b,\n,\r,\t Control character

Common Data Type Format Specifiers for fprintf


Common Control Characters
Specifier Display
Meaning Meaning
%d Integer/whole number Values
\n New line
%g Exponential
\t Tab
%c Character
%% Print a percent character
%f Fixed-point notation
\\ Print backlash
%s String
Example on Format Specifier
% Using fprintf
fprintf('%5.3f\n', 12.3456); % Output: "12.346"

fprintf('%5.3f\n', 1.2); % Output: "1.200"

fprintf('%5.3f\n', 123.456); % Output: "123.456" (exceeds width)

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

Why this matters?


Flow control structures are essential for implementing logic (e.g., checking conditions) and performing repetitive calculations (e.g., numerical
iterations, solving differential equations over time).
What are Conditional Statements?

• Purpose: Make decisions in code based on conditions

• 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"

Why Use IF Statements?

• Implement decision-making logic

• Handle different scenarios and edge cases

• Create robust programs that adapt to input data

• Enforce business rules and safety constraints


Key Components:

• if: Keyword that starts the conditional block


• condition: A logical expression that evaluates to true (1) or false (0)
• statement(s): Code to be executed if condition is true
• end: Required keyword that marks the end of the IF block
One-way IF Statement
• Executes code only if condition is true
• No action taken if condition is false

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.

% Example: Check if temperature is safe


clear
clc
T = input('Enter reactor temperature (C): ');
if T > 400
disp('WARNING: Temperature exceeds safe limit!');
disp('Activating emergency cooling...');
end
Example
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.

% Ensure positive concentration


concentration = input('Enter concentration (mol/L): ');
if concentration <= 0
disp('Error: Concentration must be positive');
concentration = 0.1; % Default safe value
end
Example
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.

% Check if conversion is within reasonable bounds


conversion = input('Enter conversion (0-1): ');
if (conversion < 0) || (conversion > 1)
disp('Error: Conversion must be between 0 and 1');
end
Two-way IF-ELSE Statement
• Two possible paths: one for true, one for false
If condition1
% Code if condition is TRUE
statement1;
statement2;
else
% Code if condition is FALSE
statement3;
statement4;
end
Example
• Write a MATLAB program that reads the Reynolds number and determines whether the flow is laminar Re <
2100 or turbulent. Based on the flow regime, the program should calculate the appropriate friction factor using
𝑓 = for laminar flow or 𝑓 = 0.316/𝑅𝑒 . for turbulent flow, and then display the resulting friction factor.
Example
• Write a MATLAB program that reads the Reynolds number and determines whether the
flow is laminar or turbulent. Based on the flow regime, the program should calculate
.
the appropriate friction factor using for laminar flow or for
turbulent flow, and then display the resulting friction factor.

% Determine flow regime based on Reynolds number


Re = input('Enter Reynolds number: ');
if Re < 2100
disp('Flow is Laminar');
friction_factor = 64 / Re;
else
disp('Flow is Turbulent');
friction_factor = 0.316 / (Re^0.25);
end
fprintf('Friction factor: %.4f\n', friction_factor);
Multi-way IF-ELSEIF-ELSE Statement

• Multiple conditions checked in sequence


• First true condition executes, rest are skipped
This conditional statement follows the format:

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.

% Process optimization decision


yield =0.85;
purity = 0.95;
cost = 120;
if (yield > 0.8) && (purity > 0.9) && (cost < 150)
disp('Process meets all optimization criteria');
disp('Proceed to scale-up phase');
elseif (yield > 0.8) && (purity > 0.9)
disp('Good yield and purity, but cost needs optimization');
else
disp('Process requires significant improvement');
end
switch/case Conditional Statement
• This conditional statement follows the format:
Switch variable_or_expression
case value1
statement1
case value2
statement2
case value3
statement3
otherwise
statement4
end
Example

• Develop a MATLAB program that converts a given temperature in in Celsius to


either Fahrenheit or Kelvin based on user choice. The user inputs 'F' for Fahrenheit
or 'K' for Kelvin. The program should perform the conversion using the formulas:
• Fahrenheit: out in
• Kelvin: out in
The program must display the converted temperature with appropriate units, or show an
error message if the user enters an invalid option.
% Process optimization decision
T_in=input(‘Enter the value of the temperature to be converted’);
choice = input(‘Enter selection Convert to (F)ahrenheit or (K)elvin? ', 's');
switch upper(choice)
case 'F’
T_out = (T_in * 9/5) + 32; fprintf('Temperature is %.2f °F\n', T_out);
case 'K’
T_out = T_in + 273.15; fprintf('Temperature is %.2f K\n', T_out);
otherwise
disp('Invalid choice.');
end
Exercise
Create a MATLAB program that accepts a temperature that is entered
by the user and convert the temperature from a given unit into another
unit chosen by the user.
Exercise
Write a general MATLAB program that will promote a user to select
from a List of Ideal gas equation Variables(P,V,T,n) to be calculated and
calculate the variable of interest.
LOOPING STATEMENTS
for Loop Statement : Repeats a block of code a fixed number of times
for index=initial:increment/decrement:final You give a vector in the "for" statement, and
Statements Matlab will loop through for each value in
the vector
End

while Loop statement : Repeats a block of code as long as a condition is true.


Initialization Repeat statements based on a condition
while condition rather than a fixed number

Statement while repeats statements WHILE its condition


increment/decrement remains true. The condition is therefore the
one to repeat and is tested each time
end BEFORE statements are repeated.
FOR Loop Structure
for Loop Statement : Repeats a block of code a fixed number of times
for index=initial:increment/decrement:final You give a vector in the "for" statement, and
Statements Matlab will loop through for each value in
the vector
End

• Index: Loop variable that changes each iteration

• Initial : Initial value of index

• Increment /decrement : Step size (default = 1 if omitted)

• Final: Final value - loop stops when index exceeds this value

• Statements: Code executed each iteration


Problem Statement (Short)
1. Create a MATLAB program that counts from 1 to 5 using a loop. For each
iteration, the program should display the iteration number at each iteration.
2. Develop a MATLAB program that counts from 2 to 10 in increments of 2 using a
loop. The program should display the value of the counter i at each step.
3. Write a MATLAB program that counts backwards from 5 to 1 using a loop. The
program should display each number in a countdown format.
% Count from 1 to 5
for i = 1:5
fprintf('Iteration Number: %d\n', i);
end

% 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

% Display results in a table


T = table(time', concentration', 'VariableNames', {'Time_sec', 'Concentration_gmol_L'});
disp(T);

% Plot the results


plot(time, concentration, '-o');
title('Zero-Order Reaction: Time vs. Concentration');
xlabel('Time (sec)');
ylabel('Concentration (gmol/L)');
grid on;
While Loop Structure
while Loop statement : Repeats a block of code as long as a condition is true.
Initialization Repeat statements based on a condition
rather than a fixed number
while condition
Statement while repeats statements WHILE its condition
remains true. The condition is therefore the
increment/decrement one to repeat and is tested each time
end BEFORE statements are repeated.

• Initialization: The starting point for the condition


• Condition: Logical expression. The loop continues as long as this condition is true.
• Statements: Code executed each iteration until condition becomes false.
• increment/decrement: condition is updated within the loop to avoid an infinite loop.
• Loop continues as long as condition evaluates to true and stops when condition becomes false
Problem Statement (Short)
1. Create a MATLAB program that counts from 1 to 5 using a loop. For each
iteration, the program should display the iteration number at each iteration.
2. Develop a MATLAB program that counts from 2 to 10 in increments of 2 using a
loop. The program should display the value of the counter i at each step.
3. Write a MATLAB program that counts backwards from 5 to 1 using a loop. The
program should display each number in a countdown format.
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.
% Count from 1 to 5
i = 1; % Initialize counter
while i <= 5
fprintf('Iteration number: %d\n’, i);
i = i + 1; % Increment counter
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

i = 1; % Initialize counter for while loop

% While loop to iterate through time array


while i <= length(time)
t = time(i);
concentration(i) = Ca0 - k * t; % Zero-order kinetics: Ca = Ca0 - k*t

% Increment counter
i = i + 1;
end

% Display results in a table


T = table(time', concentration', 'VariableNames', {'Time_sec', 'Concentration_gmol_L'});
disp(T);
% Plot the results
plot(time, concentration, '-o');
title('Zero-Order Reaction: Time vs. Concentration');
xlabel('Time (sec)');
ylabel('Concentration (gmol/L)');
grid on;
Chapter Outline
7
1

2
5

3
4

Why this matters?


Plotting → "visualizing results is key to interpreting models."
PLOTTING(Basic 2D Plot) Using plot() function
Format
>>plot(x,y)

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;

You might also like