Scientific Computing
Scientific Computing
Contents
3. Loops ........................................................................................................................................................13
Learning Outcomes
• Definition:
Scientific computing is the field focused on constructing mathematical models and using computers
to analyze and solve scientific problems.
Key Differences: Unlike general computer science, it applies programming to real-world scientific
and engineering tasks.
• Scientific modeling
This is the process of generating abstract, conceptual, graphical and mathematical models to solve
an existing scientific problem.
• Scientific model
A scientific model seems to represent empirical objects, phenomenon and physical process in a
logical and objective way.
• Modeling Language
This is an artificial language that can be used to express information or knowledge or systems in a
structure that is defined by a consistent set of rules; eg the Unified Modeling Language (UML).
These rules are used for the interpretation of the meaning of components on the structure.
• Simulation
Simulation is the implementation of a model overtime. It brings the model to live and shows how a
particular object or phenomena will behave.
• Structure
This is a fundamental and intangible notion covering the recognition, observation, nature and
stability of patterns and relationships of entities.
• System
It is a set of interacting or interdependent entities which are real or abstract but the form an
integrated whole.
• Applications:
o Weather prediction
o Simulating physical processes (e.g., car crash simulations)
o Data visualization in research
2. Data structure and Algorithms
a. Data Structures
Definition
A data structure is a way of organizing and managing data efficiently in a computer to allow for
effective operations. The goal is to enable efficient storage, retrieval, and modification of data.
1. Stacks:
Operates on the principle of Last In, First Out (LIFO).
o
Common operations:
o
▪ Push: Add an element to the top of the stack.
▪ Pop: Remove the top element.
2. Queues:
o Operates on the principle of First In, First Out (FIFO).
o Common operations:
▪ Enqueue: Add an element to the end.
▪ Dequeue: Remove the front element.
3. Trees:
o A hierarchical data structure where each node has a parent and children.
o Example: Binary trees, decision trees.
4. Graphs:
o A collection of nodes (vertices) connected by edges.
o Used in network modeling, social media, etc.
2. Algorithms
Definition
An algorithm is a finite sequence of well-defined steps to solve a specific problem. Algorithms are
the foundation of computational problem-solving.
Characteristics of Algorithms:
1. Finiteness: Must terminate after a finite number of steps.
2. Definiteness: Each step must be clearly defined.
3. Generality: Should solve all problems of a particular class.
4. Effectiveness: Operations should be basic and executable manually if required.
5. Input-Output: Accepts specific inputs and produces clear outputs.
1. Problem Formulation:
o Understand the problem and clearly define the requirements.
2. Modeling:
o If possible, express the problem in mathematical or graphical terms.
3. Design:
o Create a step-by-step solution using pseudocode or flowcharts.
4. Implementation:
o Translate the solution into a programming language.
5. Testing and Debugging:
o Evaluate the algorithm for errors and optimize as needed.
6. Evaluation:
o Analyze the algorithm for efficiency (time and space complexity).
1. Recursive Algorithms:
o Calls itself with smaller inputs until a base condition is met.
o Example: Calculating factorials or Fibonacci numbers.
o Recursive Algorithm Example: Find the k-th even number:
plaintext
Copy code
if k = 1, then return 0;
else return Even(k-1) + 2.
2. Iterative Algorithms:
o Uses loops to repeatedly execute steps.
o Example: Iterative factorial computation.
Efficiency of Algorithms
1. Time Complexity:
o Measures the execution time of an algorithm relative to the size of the input (n).
o Common time complexities:
▪ O(1)O(1)O(1): Constant time.
▪ O(logn)O(\log n)O(logn): Logarithmic time.
▪ O(n)O(n)O(n): Linear time.
▪ O(n2)O(n^2)O(n2): Quadratic time.
2. Space Complexity:
o Refers to the memory required by an algorithm to run.
• Performance depends on factors like computational time, memory requirements, and input
size.
• Algorithms are analyzed using:
o Best Case: Minimum time required.
o Worst Case: Maximum time required.
o Average Case: Expected time for random inputs.
3. Introduction to MATLAB
• What is MATLAB?
MATLAB (Matrix Laboratory) is a numerical computing tool widely used in engineering and
science for algorithm development, data analysis, and visualization.
• Features of MATLAB:
o Interactive environment for matrix and numerical computation.
o Tools for 2D and 3D plotting.
o Extensive library of built-in mathematical functions.
4. Hierarchical Data Concepts
Diagram:
Copy code
• Key Components:
o Command Window: For running commands interactively.
o Workspace: Displays active variables.
o Current Folder: Shows files in the active directory.
o Editor: Used for writing and saving scripts.
• Navigating MATLAB:
o Use the help command for documentation. Example: help plot.
o Use arrow keys to access previous commands.
• Data Types:
o Numbers: Scalars, vectors, and matrices.
o Strings: Enclosed in single quotes ('example').
o Logical: True (1) or False (0).
• Variable Naming Rules:
o Must start with a letter.
o Can include letters, digits, and underscores.
o MATLAB is case-sensitive. a ≠ A.
• Arithmetic Operators:
• Basic Commands:
a = 10;
b = 5;
sum = a + b; % Addition
diff = a - b; % Subtraction
prod = a * b; % Multiplication
quot = a / b; % Division
• MATLAB Functions:
Trigonometric calculations
x = pi;
Code:
Output: A sine wave curve with proper labels on the axes and a grid.
9. Practice Exercises
1. Compute:
o sin(π/4)
o log10(100)
o 2^3
2. Create a matrix and perform operations:
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A + B; % Matrix addition
D = A * B; % Matrix multiplication
x = 0:pi/50:2*pi;
y = cos(x);
plot(x, y, 'r--');
title('Cosine Wave');
xlabel('x');
ylabel('cos(x)');
Learning Outcomes
• Definition: Control structures are programming constructs that control the flow of
execution in a program.
• Types of control structures in MATLAB:
1. Conditional statements (if, else, elseif, switch).
2. Loops (for, while, break).
2. Conditional Statements
if condition
statements
end
Example:
x = 10;
if x > 5
disp('x is greater than 5');
end
matlab
Copy code
x = 3;
if x > 5
disp('x is greater than 5');
else
disp('x is less than or equal to 5');
end
3. if-elseif-else Statement: Adds multiple conditions.
Example:
matlab
Copy code
x = 7;
if x > 10
disp('x is greater than 10');
elseif x > 5
disp('x is greater than 5 but less than or equal to 10');
else
disp('x is less than or equal to 5');
end
4. switch Statement: Used for checking multiple conditions (more concise than if-elseif).
Syntax:
matlab
Copy code
switch variable
case value1
statements
case value2
statements
otherwise
statements
end
Example:
matlab
Copy code
grade = 'B';
switch grade
case 'A'
disp('Excellent');
case 'B'
disp('Good');
otherwise
disp('Needs improvement');
end
3. Loops
1. for Loop:
o Used for iterating over a fixed range.
o Syntax:
matlab
Copy code
statements
end
o Example:
matlab
Copy code
for i = 1:5
2. while Loop:
o Executes as long as a condition remains true.
o Syntax:
matlab
Copy code
while condition
statements
end
o Example:
matlab
Copy code
x = 0;
while x < 5
x = x + 1;
end
matlab
Copy code
for i = 1:10
if i == 5
break;
end
end
o continue: Skips to the next iteration without executing the remaining code in the
loop.
o Example:
matlab
Copy code
for i = 1:5
if i == 3
continue;
end
end
• Common Errors:
o Syntax errors (e.g., missing end statement).
o Logical errors (e.g., incorrect conditions).
o Runtime errors (e.g., invalid matrix dimensions).
• Debugging Tools:
o Use the disp function to track variable values.
o MATLAB’s built-in debugger: Set breakpoints to pause execution and inspect
variables.
• Simple Error Handling: Use the try-catch block for handling runtime errors. Example:
matlab
Copy code
try
end
5. Practice Examples
matlab
Copy code
if num > 0
disp('Positive number');
disp('Negative number');
else
disp('Zero');
end
matlab
Copy code
sum = 0;
for i = 1:10
sum = sum + i;
end
disp(['Sum: ', num2str(sum)]);
3. while Loop: Find the first number greater than 100 that is divisible by 7. Solution:
matlab
Copy code
num = 100;
while true
num = num + 1;
if mod(num, 7) == 0
break;
end
end
4. Error Handling: Write a program that divides two numbers and handles division by zero.
Solution:
matlab
Copy code
try
result = a / b;
catch
end
6. Tips for Success
Learning Outcomes
1. Introduction to Functions
• Function Structure: A MATLAB function is defined in its own file with the .m extension
and must begin with a function keyword.
Syntax:
matlab
Copy code
% Function body
end
matlab
Copy code
area = pi * radius^2;
end
Usage: Save the function in a file named circleArea.m, then call it from the command window or a
script:
matlab
Copy code
r = 5;
a = circleArea(r);
3. Scope of Variables
• Local Variables: Variables declared inside a function are local to that function and cannot
be accessed outside it.
• Global Variables: Use global to share variables across functions (not recommended unless
necessary).
Example:
matlab
Copy code
global x;
x = 10;
myFunction();
function myFunction()
global x;
end
• Subroutines: Subroutines are smaller functions designed to handle specific subtasks within a
larger program.
matlab
Copy code
% Main function
end
% Subroutine to calculate area
end
end
matlab
Copy code
rectangleProperties(5, 10);
matlab
Copy code
o Data Manipulation:
matlab
Copy code
o Plotting:
matlab
Copy code
• Syntax:
matlab
Copy code
% Function body
end
Example: Create a function to compute the sum and product of two numbers:
matlab
Copy code
sumResult = a + b;
productResult = a * b;
end
Usage:
matlab
Copy code
7. Anonymous Functions
• Anonymous functions allow you to define simple one-line functions without creating a
separate file.
• Syntax:
matlab
Copy code
Example:
matlab
Copy code
8. Practice Exercises
matlab
Copy code
result = 1;
for i = 1:n
result = result * i;
end
end
2. Multiple Outputs: Create a function to calculate the mean and standard deviation of an
array.
matlab
Copy code
meanValue = mean(data);
stdValue = std(data);
end
3. Subroutine Practice: Write a main function to calculate the volume and surface area of a
cylinder, using subroutines for each calculation.
matlab
Copy code
end
end
• Always save functions with the same name as the file (e.g., circleArea.m for circleArea
function).
• Use comments to explain the purpose of each function and input/output parameters.
• Test functions with different inputs to ensure accuracy.
• Avoid using global variables unless absolutely necessary; pass inputs and outputs explicitly
for clarity.
Learning Outcomes
1. Work with advanced data types like arrays, matrices, and structures.
2. Perform operations on cell arrays and structures.
3. Execute file input/output (I/O) operations.
4. Understand and manipulate complex data.
Arrays in MATLAB
• Definition: Arrays are lists of numbers or expressions arranged in rows and columns.
• Types:
o Row Vector: A single row of elements.
o Column Vector: A single column of elements.
o Matrix: Multiple rows and columns.
• Creating arrays:
• rowVector = [1, 2, 3, 4];
• columnVector = [1; 2; 3; 4];
• Accessing elements:
• element = matrix(2, 3); % Access row 2, column 3
• row = matrix(2, :); % Access entire row 2
• Common operations:
o Addition/Subtraction: A + B, A - B
o Multiplication:
▪ Element-wise: A .* B
▪ Matrix multiplication: A * B
o Transposition: A'
Matrix Manipulations
• Reshape:
• Concatenation:
• combined = [A, B]; % Horizontal concatenation
1. Basics of Indexing
In MATLAB, matrices are accessed using row and column indices in the format:
matlab
Copy code
M(row, column)
Example:
Accessing an Element:
matlab
Copy code
You can use the colon operator (:) to select all rows or all columns.
• To get row 1:
matlab
Copy code
• To get column 2:
matlab
Copy code
3. Accessing Submatrices
You can extract a submatrix by specifying a range of rows and columns using the colon operator (:).
Example:
matlab
Copy code
% Output:
% submatrix = [9 12;
% 5 6]
Explanation:
Instead of a range, you can pick specific rows or columns using square brackets [ ].
Example:
For MMM:
Copy code
% Output:
% submatrix = [9 12;
% 8 9]
Explanation:
The colon operator (:) can also be used to select all elements in a matrix.
Example:
For MMM:
matlab
Copy code
vector = M(:);
% Output:
Copy code
matlab
Copy code
matlab
Copy code
% Output:
% columns = [9 12 15;
% 4 4 4;
% 1 0 -1;
% -4 -2 0]
2. Cell Arrays and Structures
Cell Arrays
• Definition: Cell arrays can store different types of data in the same array.
• Creation:
• Accessing elements:
o Curly braces {} return the content of a cell:
Structures
• Definition: Structures group data into fields, with each field containing a name and value.
• Creation:
• student.name = 'John';
• student.age = 20;
• Accessing fields:
name = student.name;
• Array of structures:
• students(1).name = 'Alice';
• students(1).age = 22;
• students(2).name = 'Bob';
students(2).age = 23;
Complex Numbers
• MATLAB supports operations on complex numbers.
• Creating complex numbers:
z = 3 + 4i;
• Operations:
• realPart = real(z); % Extract real part
• imagPart = imag(z); % Extract imaginary part
• magnitude = abs(z); % Compute magnitude
Examples:
2. Complex arithmetic:
3. z1 = 2 + 3i;
4. z2 = 4 - 5i;
5. sum = z1 + z2;
product = z1 * z2;
• Text Files:
• Excel Files:
• Text Files:
• Excel Files:
writetable(T, 'output.xlsx'); % Writes table T to an Excel file
disp(B);
disp(student);
5. Practice Exercises
1. Matrix Operations:
o Create a 3x3 matrix and compute its transpose, inverse, and determinant.
o Multiply it element-wise by another matrix of the same size.
2. Cell Array Manipulation:
o Create a 2x2 cell array containing a string, number, and a matrix.
o Replace one of the cells with a new value.
3. Structure Manipulation:
o Create a structure representing a book with fields: title, author, and pages.
o Access the fields and display the information.
4. Complex Numbers:
o Create a matrix of complex numbers and compute their magnitudes and angles.
5. File I/O:
o Write a 4x4 matrix to a file and read it back.
o Save a structure to a .mat file and reload it.
Objective:
Key Topics:
Key Concepts:
2. Linear Algebra: Vectors, Matrices, and Eigenvalues
• Linear Algebra in MATLAB:
o Matrix Creation:
matlab
Copy code
A = [1, 2; 3, 4];
o Matrix Multiplication:
matlab
Copy code
B = [5, 6; 7, 8];
C = A * B;
Key Concepts:
matlab
Copy code
B = [1; 3];
matlab
Copy code
A = [2, 1; 1, 3];
disp(D); % Eigenvalues
disp(V); % Eigenvectors
1. Descriptive Statistics:
o Mean: mean(data)
o Standard Deviation: std(data)
o Variance: var(data)
2. Curve Fitting Using Polynomial Regression:
o Fit a polynomial to data:
matlab
Copy code
x = [1, 2, 3, 4];
3. Correlation Coefficient:
o Measure linear relationship between two datasets:
matlab
Copy code
x = [1, 2, 3];
y = [2, 4, 6];
Practice Problems:
1. Numerical Methods:
o Use the Newton-Raphson method to find the root of
2. Linear Algebra:
o Solve the system of equations
o Calculate the eigenvalues of the matrix:
3. Statistical Analysis:
o Fit a quadratic polynomial to the following data: