SCIENTIFIC COMPUTING
Contents
Week 1: Introduction to Scientific Computing and MATLAB ................................................................... 2
1. Scientific Computing Overview .............................................................................................................. 3
2. Data structure and Algorithms ............................................................................................................... 4
3. Introduction to MATLAB ....................................................................................................................... 7
4. Hierarchical Data Concepts ..................................................................................................................... 8
5. MATLAB Environment Overview ........................................................................................................ 8
6. Basic MATLAB Syntax ............................................................................................................................ 8
7. Practice with Basic MATLAB Calculations........................................................................................... 9
8. Example: Plotting a Sine Wave..............................................................................................................10
9. Practice Exercises ....................................................................................................................................10
Week 2: Control Structures and Basic Programming Constructs .............................................................11
1. Introduction to Control Structures ......................................................................................................11
2. Conditional Statements ..........................................................................................................................11
3. Loops ........................................................................................................................................................13
4. Debugging and Error Handling ............................................................................................................15
5. Practice Examples ...................................................................................................................................16
Week 3: Functions and Subroutines ..............................................................................................................18
1. Introduction to Functions .....................................................................................................................18
2. Creating Functions in MATLAB ..........................................................................................................18
3. Scope of Variables ..................................................................................................................................19
4. Subroutines and Modular Programming .............................................................................................20
5. Built-in MATLAB Functions ................................................................................................................21
6. Writing Functions with Multiple Outputs ...........................................................................................22
7. Anonymous Functions ...........................................................................................................................23
8. Practice Exercises ....................................................................................................................................23
Week 4: Advanced Data Types and Operations ..........................................................................................25
1. Arrays and Matrices: Operations and Manipulations ........................................................................25
2. Cell Arrays and Structures .....................................................................................................................31
3. Complex Data Types ..............................................................................................................................31
4. File Input/Output Operations ..............................................................................................................32
5. Practice Exercises ....................................................................................................................................33
Week 5: Mathematical Foundations for Scientific Computing ..................................................................34
1. Numerical Methods: Basic Algorithms and Applications .................................................................34
2. Linear Algebra: Vectors, Matrices, and Eigenvalues ..........................................................................36
3. Statistical Analysis and Data Fitting .....................................................................................................37
Week 1: Introduction to Scientific Computing and MATLAB
Learning Outcomes
By the end of this week, you should be able to:
1. Understand the basics of scientific computing and its applications.
2. Navigate the MATLAB environment and perform basic operations.
3. Define hierarchical data concepts and their significance in computing.
4. Use basic MATLAB syntax for variable manipulations and calculations.
1. Scientific Computing Overview
• 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.
Key Features of Data Structures:
• Efficiency: Optimized for time and space when performing operations.
• Organization: Data elements are structured based on their relationships, improving access
and management.
• Abstract Data Type (ADT): A logical description of the behavior of a data structure,
independent of its implementation.
Types of Data Structures
1. Simple Data Structures:
o Built from primitive data types (e.g., integers, characters).
o Examples: Arrays, variables, pointers.
2. Compound Data Structures:
o Created by combining primitive data types.
o Subcategories:
▪ Linear Data Structures: Data elements are arranged sequentially.
▪ Examples: Lists, Stacks, Queues.
▪ Operations:
▪ Add an element: Append data to the structure.
▪ Delete an element: Remove a specific element.
▪ Traverse: Iterate over all elements.
▪ Sort: Organize elements in a specific order.
▪ Search: Find a specific element.
▪ Non-Linear Data Structures: Data elements are arranged in a hierarchical
or graph-like structure.
▪ Examples: Trees, Graphs.
▪ Operations:
▪ Add and delete elements.
▪ Display data in hierarchical order.
Examples of Common Data Structures:
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.
Steps for Designing an Algorithm
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).
Approaches to Designing Algorithms:
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.
Analyzing Algorithm Performance
• 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.
Comparison: Recursive vs. Iterative Algorithms
Feature Recursive Iterative
Memory Usage Uses more memory (stack frames) More efficient (single loop)
Code Length Concise and shorter Typically longer
Performance Slower due to function calls Faster in most cases
Termination Requires a base case Terminates when loop condition fails
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
• Data Hierarchy Overview: Data processed by computers is structured in layers:
1. Bits: The smallest data unit (0 or 1).
2. Bytes: 8 bits combine to represent characters like letters or numbers.
3. Fields: A set of characters representing a single data item (e.g., Name).
4. Records: A group of related fields (e.g., a student's record with name, ID, and
grades).
5. Files: Collection of related records (e.g., a file with all student records).
6. Databases: Multiple files organized for easier access.
Diagram:
Copy code
Bits → Bytes → Fields → Records → Files → Databases
5. MATLAB Environment Overview
• 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.
6. Basic MATLAB Syntax
• 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:
Operator Description Example
+ Addition 3+2=5
Operator Description Example
- Subtraction 5-3=2
* Multiplication 4 * 2 = 8
/ Division 6/2=3
^ Exponentiation 2^3 = 8
7. Practice with Basic MATLAB Calculations
• Basic Commands:
Assign values to variables
a = 10;
b = 5;
Perform basic calculations
sum = a + b; % Addition
diff = a - b; % Subtraction
prod = a * b; % Multiplication
quot = a / b; % Division
expo = a^b; % Exponentiation
disp(['Sum: ', num2str(sum)]); % Display the sum
• MATLAB Functions:
Trigonometric calculations
x = pi;
y = sin(x); % Sine function
z = cos(x); % Cosine function
disp(['sin(pi): ', num2str(y)]);
disp(['cos(pi): ', num2str(z)]);
8. Example: Plotting a Sine Wave
Code:
% Define x values from 0 to 2π
x = 0:pi/100:2*pi;
% Compute sine values
y = sin(x);
% Plot the sine wave
plot(x, y);
title('Sine Wave');
xlabel('x');
ylabel('sin(x)');
grid on;
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
3. Plot a cosine wave from 0 to 2π2\pi2π with the code:
x = 0:pi/50:2*pi;
y = cos(x);
plot(x, y, 'r--');
title('Cosine Wave');
xlabel('x');
ylabel('cos(x)');
10. Tips for Success
• Always save your scripts to avoid retyping code. Use .m file extension.
• Use comments (%) to annotate your code.
• If you encounter errors, check for typos or incorrect variable names.
Week 2: Control Structures and Basic Programming Constructs
Learning Outcomes
By the end of this week, you should be able to:
1. Understand and implement control flow in MATLAB using conditional statements.
2. Use loops (for, while) and control flow modifiers (break).
3. Differentiate between executable and non-executable statements.
4. Debug simple errors in MATLAB programs.
1. Introduction to Control Structures
• 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
Syntax and Examples:
1. if Statement: Executes a block of code if a condition is true.
Syntax:
if condition
statements
end
Example:
x = 10;
if x > 5
disp('x is greater than 5');
end
2. if-else Statement: Adds an alternative action if the condition is false.
Example:
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
Loops allow repeated execution of code blocks.
1. for Loop:
o Used for iterating over a fixed range.
o Syntax:
matlab
Copy code
for index = start:step:end
statements
end
o Example:
matlab
Copy code
for i = 1:5
disp(['Iteration: ', num2str(i)]);
end
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
disp(['x is: ', num2str(x)]);
x = x + 1;
end
3. Control Flow Modifiers:
o break: Exits the loop prematurely.
o Example:
matlab
Copy code
for i = 1:10
if i == 5
disp('Breaking the loop');
break;
end
disp(['Iteration: ', num2str(i)]);
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
disp(['Iteration: ', num2str(i)]);
end
4. Debugging and Error Handling
• 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
result = 10 / 0; % Division by zero will cause an error
catch
disp('An error occurred. Check your input values.');
end
5. Practice Examples
1. Conditional Statements: Write a MATLAB program to check if a number is positive,
negative, or zero. Solution:
matlab
Copy code
num = input('Enter a number: ');
if num > 0
disp('Positive number');
elseif num < 0
disp('Negative number');
else
disp('Zero');
end
2. for Loop: Compute the sum of integers from 1 to 10. Solution:
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
disp(['First number greater than 100 divisible by 7: ', num2str(num)]);
break;
end
end
4. Error Handling: Write a program that divides two numbers and handles division by zero.
Solution:
matlab
Copy code
a = input('Enter numerator: ');
b = input('Enter denominator: ');
try
result = a / b;
disp(['Result: ', num2str(result)]);
catch
disp('Error: Division by zero is not allowed.');
end
6. Tips for Success
• Always indent your code for better readability.
• Use comments (%) to explain your logic.
• Break complex problems into smaller steps before writing code.
• Test your code for edge cases (e.g., dividing by zero or empty inputs).
Week 3: Functions and Subroutines
Learning Outcomes
By the end of this week, you should be able to:
1. Create and use custom functions in MATLAB.
2. Understand the concept of modular programming with subroutines.
3. Utilize built-in MATLAB functions effectively.
4. Define the scope of variables within functions.
5. Write reusable and efficient code with functions and subroutines.
1. Introduction to Functions
• Definition: A function is a self-contained block of code designed to perform a specific task.
• Advantages:
o Encourages code reuse.
o Simplifies debugging by isolating code blocks.
o Improves readability and modularity of programs.
2. Creating Functions in MATLAB
• 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 [output1, output2, ...] = functionName(input1, input2, ...)
% Function body
end
Example: Create a function to calculate the area of a circle:
matlab
Copy code
function area = circleArea(radius)
% Calculates the area of a circle given the radius
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);
disp(['Area of the circle: ', num2str(a)]);
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;
disp(['Global variable x: ', num2str(x)]);
end
4. Subroutines and Modular Programming
• Subroutines: Subroutines are smaller functions designed to handle specific subtasks within a
larger program.
Example: A program to calculate the perimeter and area of a rectangle:
matlab
Copy code
% Main function
function rectangleProperties(length, width)
area = calculateArea(length, width);
perimeter = calculatePerimeter(length, width);
disp(['Area: ', num2str(area)]);
disp(['Perimeter: ', num2str(perimeter)]);
end
% Subroutine to calculate area
function area = calculateArea(length, width)
area = length * width;
end
% Subroutine to calculate perimeter
function perimeter = calculatePerimeter(length, width)
perimeter = 2 * (length + width);
end
Save the above code as rectangleProperties.m and call it:
matlab
Copy code
rectangleProperties(5, 10);
5. Built-in MATLAB Functions
• MATLAB provides a wide array of built-in functions for various purposes.
• Examples:
o Mathematical Functions:
matlab
Copy code
sqrt(16); % Square root
log10(100); % Logarithm base 10
sin(pi/4); % Sine function
o Data Manipulation:
matlab
Copy code
mean([1, 2, 3]); % Average of an array
sort([3, 1, 2]); % Sort an array
o Plotting:
matlab
Copy code
plot(x, y); % Basic plot
6. Writing Functions with Multiple Outputs
• Syntax:
matlab
Copy code
function [output1, output2] = myFunction(input1, input2)
% Function body
end
Example: Create a function to compute the sum and product of two numbers:
matlab
Copy code
function [sumResult, productResult] = calculateSumAndProduct(a, b)
sumResult = a + b;
productResult = a * b;
end
Usage:
matlab
Copy code
[sumValue, productValue] = calculateSumAndProduct(5, 3);
disp(['Sum: ', num2str(sumValue)]);
disp(['Product: ', num2str(productValue)]);
7. Anonymous Functions
• Anonymous functions allow you to define simple one-line functions without creating a
separate file.
• Syntax:
matlab
Copy code
f = @(x) x^2 + 2*x + 1; % Function definition
result = f(5); % Function call
Example:
matlab
Copy code
square = @(x) x^2;
disp(['Square of 4: ', num2str(square(4))]);
8. Practice Exercises
1. Basic Function: Write a function to calculate the factorial of a number.
matlab
Copy code
function result = factorial(n)
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
function [meanValue, stdValue] = calculateStats(data)
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
function cylinderProperties(radius, height)
volume = calculateVolume(radius, height);
surfaceArea = calculateSurfaceArea(radius, height);
disp(['Volume: ', num2str(volume)]);
disp(['Surface Area: ', num2str(surfaceArea)]);
end
function volume = calculateVolume(radius, height)
volume = pi * radius^2 * height;
end
function surfaceArea = calculateSurfaceArea(radius, height)
surfaceArea = 2 * pi * radius * (radius + height);
end
4. Anonymous Function: Create an anonymous function to compute the quadratic formula
roots for given a, b, and c.
9. Tips for Success
• 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.
Week 4: Advanced Data Types and Operations
Learning Outcomes
By the end of this week, you should be able to:
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.
1. Arrays and Matrices: Operations and Manipulations
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.
Basic Array Operations
• Creating arrays:
• rowVector = [1, 2, 3, 4];
• columnVector = [1; 2; 3; 4];
matrix = [1, 2, 3; 4, 5, 6; 7, 8, 9];
• Accessing elements:
• element = matrix(2, 3); % Access row 2, column 3
• row = matrix(2, :); % Access entire row 2
column = matrix(:, 3); % Access entire column 3
• 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:
reshapedMatrix = reshape(matrix, 1, 9); % Reshape to 1 row, 9 columns
• Concatenation:
• combined = [A, B]; % Horizontal concatenation
stacked = [A; B]; % Vertical concatenation
• Inverse and Determinants:
• inverseMatrix = inv(A); % Inverse of matrix A
determinant = det(A); % Determinant of matrix A
1. Basics of Indexing
In MATLAB, matrices are accessed using row and column indices in the format:
matlab
Copy code
M(row, column)
Example:
For the matrix:
Accessing an Element:
• To access the element in row 2, column 3:
matlab
Copy code
element = M(2, 3); % Output: 6
2. Accessing Entire Rows or Columns
You can use the colon operator (:) to select all rows or all columns.
Access an Entire Row:
• To get row 1:
matlab
Copy code
row = M(1, :); % Output: [6 9 12]
Access an Entire Column:
• To get column 2:
matlab
Copy code
column = M(:, 2); % Output: [9; 5; 8]
3. Accessing Submatrices
You can extract a submatrix by specifying a range of rows and columns using the colon operator (:).
Example:
For MMM (same as above):
Extract Rows 1-2 and Columns 2-3:
matlab
Copy code
submatrix = M(1:2, 2:3);
% Output:
% submatrix = [9 12;
% 5 6]
Explanation:
• 1:2 → Select rows 1 and 2.
• 2:3 → Select columns 2 and 3.
4. Accessing Specific Rows/Columns
Instead of a range, you can pick specific rows or columns using square brackets [ ].
Example:
For MMM:
Extract Rows 1 and 3, Columns 2 and 3:
matlab
Copy code
submatrix = M([1 3], [2 3]);
% Output:
% submatrix = [9 12;
% 8 9]
Explanation:
• [1 3] → Select rows 1 and 3.
• [2 3] → Select columns 2 and 3.
5. The Colon Operator for All Elements
The colon operator (:) can also be used to select all elements in a matrix.
Example:
For MMM:
Convert the Matrix to a Column Vector:
matlab
Copy code
vector = M(:);
% Output:
% vector = [6; 9; 12; 4; 5; 6; 7; 8; 9]
6. Putting It All Together
Let’s revisit the original problem matrix:
Example 1: Access Element at Row 3, Column 4
matlab
Copy code
element = M(3, 4); % Output: -1
Example 2: Extract Entire Row 2
matlab
Copy code
row = M(2, :); % Output: [4 4 4 4 4 4]
Example 3: Extract Columns 2 to 4
matlab
Copy code
columns = M(:, 2:4);
% 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:
cellArray = {1, 'text', [2, 3, 4]; 'row2', pi, eye(3)};
• Accessing elements:
o Curly braces {} return the content of a cell:
content = cellArray{1, 2};
o Parentheses () return the cell itself:
cellRef = cellArray(1, 2);
• Manipulating cell arrays:
cellArray{2, 1} = 'new value';
Structures
• Definition: Structures group data into fields, with each field containing a name and value.
• Creation:
• [Link] = 'John';
• [Link] = 20;
[Link] = [90, 85, 88];
• Accessing fields:
name = [Link];
• Array of structures:
• students(1).name = 'Alice';
• students(1).age = 22;
• students(2).name = 'Bob';
students(2).age = 23;
3. Complex Data Types
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
angle = angle(z); % Compute angle in radians
Examples:
1. Matrix with complex numbers:
complexMatrix = [1+2i, 3-4i; 5+6i, 7-8i];
2. Complex arithmetic:
3. z1 = 2 + 3i;
4. z2 = 4 - 5i;
5. sum = z1 + z2;
product = z1 * z2;
4. File Input/Output Operations
Reading Data from Files
• Text Files:
data = readmatrix('[Link]'); % Reads numeric data from text file
• Excel Files:
data = readtable('[Link]'); % Reads data into a table
Writing Data to Files
• Text Files:
writematrix(A, '[Link]'); % Writes matrix A to a text file
• Excel Files:
writetable(T, '[Link]'); % Writes table T to an Excel file
Example: File Operations
1. Write and Read a Matrix:
2. % Write matrix to file
3. A = [1, 2, 3; 4, 5, 6];
4. writematrix(A, '[Link]');
5.
6. % Read matrix from file
7. B = readmatrix('[Link]');
disp(B);
8. Write a structure to a file:
9. % Create structure
10. [Link] = 'Jane';
11. [Link] = 21;
12. save('[Link]', 'student'); % Save to .mat file
13.
14. % Load structure
15. load('[Link]');
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.
Tips for Success
• Use help and doc commands in MATLAB to explore functions (e.g., doc cell for cell arrays).
• Use clear variable names to make code readable and maintainable.
• Always check file paths when working with file I/O.
• Debug step-by-step to ensure correctness of matrix operations, especially dimensions.
Week 5: Mathematical Foundations for Scientific Computing
Objective:
• Understand and apply mathematical concepts fundamental to scientific computing.
• Learn to implement basic numerical methods, linear algebra operations, and statistical
analysis in MATLAB.
Key Topics:
1. Numerical Methods: Basic Algorithms and Applications
2. Linear Algebra: Vectors, Matrices, and Eigenvalues
3. Statistical Analysis and Data Fitting
1. Numerical Methods: Basic Algorithms and Applications
• Definition: Numerical methods are techniques used to approximate solutions to
mathematical problems that may not have exact solutions.
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:
1. Solving Linear Systems:
o Represent equations AX=BAX = BAX=B as matrices.
o Example Implementation:
matlab
Copy code
A = [2, -1; -1, 2];
B = [1; 3];
X = A\B; % MATLAB's left division operator
disp(X); % Outputs solution vector
2. Eigenvalues and Eigenvectors:
o Eigenvalues satisfy Av=λvAv = \lambda vAv=λv.
o Example Implementation:
matlab
Copy code
A = [2, 1; 1, 3];
[V, D] = eig(A); % V contains eigenvectors, D contains eigenvalues
disp(D); % Eigenvalues
disp(V); % Eigenvectors
3. Statistical Analysis and Data Fitting
Key Concepts:
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];
y = [2.1, 4.2, 6.3, 8.4];
p = polyfit(x, y, 1); % Fits a line (degree 1 polynomial)
y_fit = polyval(p, x);
plot(x, y, 'o', x, y_fit, '-');
3. Correlation Coefficient:
o Measure linear relationship between two datasets:
matlab
Copy code
x = [1, 2, 3];
y = [2, 4, 6];
corrCoeff = corrcoef(x, y);
disp(corrCoeff); % Correlation matrix
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:
o Find the mean and standard deviation of yyy.