0% found this document useful (0 votes)
7 views

Lecture5_Computing

MATlab programming 5

Uploaded by

AMDCrafto
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)
7 views

Lecture5_Computing

MATlab programming 5

Uploaded by

AMDCrafto
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
You are on page 1/ 36

Computing and Software Engineering

GET211

Emmanuel Ali
Ayibaemi Ledum Jaafaru Sanusi

November 15, 2024

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 1 / 36
Outline

1 Introduction

2 Introduction to MATLAB

3 Data Type

4 Inputs and Outputs

5 Problem Solving Strategies

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 2 / 36
Problem Solving Strategies
Problem-solving in programming is a structured approach that involves breaking down
complex challenges into manageable parts, creating logical sequences to solve these parts,
and integrating them into a cohesive solution. This approach generally involves several key
steps, each contributing to the effectiveness, efficiency, and accuracy of the final program.
1. Understanding the Problem This initial phase is crucial for setting a solid
foundation. A person must interpret the requirements, clarify ambiguities, and comprehend
what the final outcome should achieve.
2. Planning the Approach: Once the problem is well-understood, creating a structured
plan is essential. This involves breaking down the problem into smaller, more manageable
parts and deciding on the overall flow and structure.
3. Divide and Conquer: Complex problems can be daunting if tackled as a whole.
Breaking the problem down into functions, modules, or classes simplifies each part and
makes it easier to focus on individual tasks.
4. Writing and Testing Incrementally Writing code in small sections and testing each
one before proceeding is crucial to catch errors early.
5. Debugging and Iteration: Errors and unexpected behaviors are natural in
programming. Debugging involves systematically locating and correcting these issues.
6. Optimization: After achieving a working solution, efficiency improvements are often
beneficial. Optimization helps to make the code faster, use less memory, or perform better
under certain conditions.
7. Reflecting and Documenting: Reflection involves reviewing what worked well,
identifying areas for improvement, and considering alternate approaches. Write clear and
detailed documentation for other developers or for future reference.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 3 / 36
Problem-Solving Strategies

• Read requirements
• Identify inputs/outputs
1. Problem Analysis • List constraints
• Write test cases
• Create examples
• Break into subtasks
• Choose algorithms
2. Solution Design • Select data structures
• Write pseudocode
Tools: • Plan architecture
• Write clean code
• IDE/Editor
• Follow standards
• Debugger Iterative Im-
3. Implementation • Add comments
• Profiler provement
• Handle errors
• Version Control
• Version control
• Documentation • Unit testing
• Integration tests
4. Testing & Debug • Debug errors
• Edge cases
• Code review
• Profile code
• Improve efficiency
5. Optimization • Refactor
• Documentation
• Maintenance

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 4 / 36
Problem solving strategy
Example of problem solving in MATLAB
Try solving a problem to find the area and perimeter of a circle given the
radius. Using these strategies:
1. Understand the Problem:
- Input: ‘radius‘
- Output: ‘area‘ and ‘perimeter‘
- Requirement: Use MATLAB formulas.
2. Plan Your Approach:
- Use the formulas area = π × radius2 and perimeter = 2 × π × radius.
3. Divide and Conquer:
- Create two separate calculations for area and perimeter.
4. Write and Test Incrementally:
- Start by testing with a sample radius to check calculations.
5. Debugging:
- Ensure that ‘pi‘ is used correctly in calculations.
6. Optimize and Reflect:
- Reflect on whether the code is efficient and consider adding comments for
clarity.
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 5 / 36
Algorithm Development
Algorithm development is the systematic process of creating a step-by-step
procedure to solve a specific problem or perform a particular task. It involves
analyzing the problem, defining the objectives and constraints, designing an
efficient approach, implementing the solution in code, testing it for accuracy
and efficiency, and refining it to ensure optimal performance.
Stages in algorithm development:
1. Problem Analysis: Carefully understanding the problem requirements,
constraints, and expected outcomes. This step involves identifying inputs,
defining the expected outputs, and understanding any special conditions or
edge cases that could affect the algorithm’s logic.
2. Objective Definition: Setting goals for the algorithm, such as speed,
memory efficiency, precision, or scalability. Depending on the requirements,
the algorithm may need to prioritize one objective (like low memory usage)
over others (such as processing speed).
3. Algorithm Design: Crafting the sequence of operations to reach the
solution. The design phase often includes:
- Choosing the strategy: Common strategies include brute force, divide and
conquer, dynamic programming, and greedy approaches.
- Pseudocode/Flowchart: Writing pseudocode or creating a flowchart to
outline the sequence of steps visually.
- Data Structures: Selecting the data structures that best suit the problem
and improve efficiency, such as arrays, linked lists, or trees.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 6 / 36
Algorithm Development
4. Implementation: Writing the code based on the algorithm design,
following programming best practices for readability and modularity.
5. Testing and Validation: Running the algorithm with various inputs,
especially edge cases, to confirm it produces correct and reliable results. This
stage ensures the algorithm behaves as expected and meets the initial
requirements.
6. Optimization: Improving the algorithm to make it faster or more
memory-efficient, often by analyzing and reducing its time and space
complexity.
7. Documentation and Review: Documenting the code, including
assumptions and edge cases, for maintainability, and often having peers
review it for clarity and correctness.
8. Deployment and Iterative Refinement: After deployment, gathering
feedback and data on the algorithm’s real-world performance can reveal new
ways to optimize or refine it for further improvements.
Algorithm development is both a creative and structured approach to
problem-solving. It combines logical reasoning and technical expertise to
create solutions that are both correct and efficient in real-world applications.
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 7 / 36
Algorithm Development Process

• Define in-
put/output
• Identify con-
straints
Problem Analysis • Set performance
goals
• Analyze require-
ments
• Create test cases

• Choose ap-
proach:
- Divide & Con-
quer
- Greedy Method
Algorithm Design
- Dynamic Pro-
gramming
- Backtracking
• Write pseu-
• Profile code docode
• Memory opti-
mization
• Time optimiza-
Optimization
tion
• Code refactoring
• Performance
tuning

• Unit testing • Time complexity


• Integration test- • Space complex-
ing ity
• Performance • Best/Worst
Testing Complexity Analysis
testing cases
• Edge case vali- • Average case
dation • Asymptotic
• Stress testing analysis
No

• Code the algo-


MeetsRequirements? rithm
• Handle edge
cases
Implementation
• Error handling
Yes • Documentation
• Code organiza-
tion

Final Algorithm

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 8 / 36
Pseudocode

Pseudocode is an informal, human-readable description of the steps and logic


needed to solve a problem or perform a task. It uses plain language mixed
with some programming-like structure without strict syntax rules, making it
easy to understand and convert into actual code.
Advantages of Pseudocode
- Readability: It’s easy for anyone with a basic understanding of programming
to read and understand.
- Algorithm Focused: Allows you to concentrate on the logic without worrying
about syntax.
- Flexible: Pseudocode can be adapted to any programming language once
the logic is solid.
Pseudocode provides a bridge between the algorithm design and actual
implementation, making it easier to plan, communicate, and refine an
algorithm before coding.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 9 / 36
Category Convention Example
INPUT INPUT number
Input/Output OUTPUT OUTPUT ”Hello World”
DISPLAY DISPLAY result
Assignment SET x = 5
Declaration DECLARE integer x
Variables
Increment INCREMENT counter
Decrement DECREMENT counter
IF condition THEN
If statement statements
Conditional END IF
IF condition THEN
statements
If-Else ELSE
statements
END IF
FOR i = 1 TO n DO
For loop statements
END FOR
WHILE condition DO
Loops While loop statements
END WHILE
REPEAT
Repeat-Until statements
UNTIL condition
FUNCTION name(parameters)
Function declaration statements
RETURN value
Functions END FUNCTION
PROCEDURE name(parameters)
Procedure declaration statements
END PROCEDURE
Array declaration DECLARE ARRAY numbers[size]
Arrays Array access SET x = array[index]
Array assignment SET array[index] = value
Single line // This is a comment
Comments /* This is a
Multiple lines multiple line
comment */
Logical operators AND, OR, NOT
Boolean
Comparison operators =, ∼=, <, >, <=, >=

Table 1: Common Pseudocode Conventions

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 10 / 36
Pseudocode Structure

Basic Elements Control Structures Functions & Procedures

• Input/Output • IF-THEN-ELSE • Function header


• Assignment • WHILE loops • Parameters
• Variables • FOR loops • Return values
• Constants • REPEAT-UNTIL • Local variables
• Comments • CASE statements • Procedure calls

Example: IF age >= 18 FUNCTION cal-


READ number THEN cArea(length,
SET sum = 0 SET status = width)
DISPLAY result ”adult” RETURN length *
// Comment ELSE width
SET status = ”mi- END FUNCTION
nor” Error Handling
Data Structures
END IF

• Arrays • TRY-CATCH
• Lists blocks
• Stacks • Error messages
• Queues • Input validation
Style Guidelines:
• Dictionaries • Exception han-
• Consistent inden-
dling
DECLARE ar- tation
• Error codes
ray[10] • Clear naming
SET queue = Emp- • Modular structure TRY
tyQueue() • Single responsibil- operation()
PUSH item TO ity CATCH error
stack • Proper documen- DISPLAY ”Error”
tation END TRY

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 11 / 36
Pseudocode Example
Provide the pseudocode to find Maximum Value in a List
1. Input: A list of numbers ‘nums‘.
2. Output: The maximum value in the list.
Pseudocode:
PROCEDURE FindMaximum(numbers)
IF length of numbers = 0 THEN
RETURN null
END IF

SET max = numbers[0]

FOR i = 1 TO length of numbers - 1 DO


IF numbers[i] > max THEN
SET max = numbers[i]
END IF
END FOR

RETURN max
END PROCEDURE
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 12 / 36
Pseudocode Example
Provide the pseudocode to check if a Number is Prime
1. Input: A positive integer ‘n‘.
2. Output: Boolean value (‘true‘ or ‘false‘) indicating whether ‘n‘ is prime.
Pseudocode:

FUNCTION is_prime(n)
IF n <= 1 THEN
RETURN false
END IF

FOR i FROM 2 TO sqrt(n) // Loop through possible divisors up to


IF n MOD i == 0 THEN // If n is divisible by i
RETURN false
END IF
END FOR

RETURN true
END FUNCTION

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 13 / 36
Flowchart
Flowcharts are a visual representation of an algorithm or process. They
use standardized symbols to represent different types of operations or
steps, helping to understand the flow of the program or process.
Flowchart Symbols
1. Oval (Start/End):
- Represents the start or end of the process.
- Example: ”Start” or ”End”.
2. Rectangle (Process):
- Represents a process or operation, such as calculations or variable
assignments.
- Example: ”a = b + c”.
3. Parallelogram (Input/Output):
- Represents input or output operations.
- Example: ”Input x” or ”Display result”.
4. Diamond (Decision):
- Represents a decision point where the flow branches based on a
condition.
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 14 / 36
Standard Flowchart Symbols
Symbol
Visual Result
Name
Terminal Start/End

Process Process

Decision Decision

Input/Output I/O

Connector 1

Document Doc

Database Data

Preparation Prep

Display Display

Manual Input Input


Flow Line

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 15 / 36
Draw a flowchart for the algorithm that checks if a number is prime.
The pseudocode used is the one discussed earlier.
Flowchart: Determine if a Number is Prime
Start

Input
number n

Yes Output
Is n <= 1?
”Not Prime”

No

Set i = 2


Is i <= n?

No Yes

Output Is n divis- No
Increment i
“Prime” ible by i?

Yes

Output
”Not Prime”

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 16 / 36
Flowchart: Finding the Largest of Three Numbers
Start

Input three Assumes three


numbers distinct numbers
a, b, c are provided

Set max = a

Yes
Is b > max? Set max = b

No

Yes
Is c> max? Set max = c

No

Output max

End
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 17 / 36
Control Structures in MATLAB

Control structures in MATLAB are essential for managing the flow of


execution in a program. The most common control structures include:
Conditional Statements (if, else, elseif, switch)
Loops (for, while)
Break and Continue
These structures enable decision-making, and iteration within the
program.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 18 / 36
Conditional Statements

Conditional statements allow the program to execute specific blocks of


code based on logical conditions. MATLAB provides the following
conditional statements:
if statement: Executes code if a condition is true.
else statement: Executes code if the if condition is false.
elseif statement: Checks multiple conditions in a sequence.
switch statement: Executes one block of code based on the
value of a variable.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 19 / 36
Conditional Statements

if Statement
The ‘if‘ statement is used to execute a block of code if a condition is
true.
Syntax:
1 if condition
2 % Code to execute if condition is true
3 end

Example:
1 x = 5;
2 if x > 3
3 disp ( ’x is greater than 3 ’) ;
4 end

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 20 / 36
Conditional Statements
if - else Statement
The ‘else‘ statement is executed when the ‘if‘ condition is false.
Syntax:
1 if condition
2 % Code if true
3 else
4 % Code if false
5 end

Example:
1 x = 2;
2 if x > 3
3 disp ( ’x is greater than 3 ’) ;
4 else
5 disp ( ’x is less than or equal to 3 ’) ;
6 end

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 21 / 36
elseif Statement
The ‘elseif‘ statement is used when there are multiple conditions to check.
Syntax:
1 if condition1
2 % Code for condition1
3 elseif condition2
4 % Code for condition2
5 else
6 % Code if all conditions are false
7 end
Example:
1 x = 5;
2 if x > 10
3 disp ( ’x is greater than 10 ’) ;
4 elseif x > 3
5 disp ( ’x is greater than 3 but less than or equal
to 10 ’) ;
6 else
7 disp ( ’x is less than or equal to 3 ’) ;
8 end
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 22 / 36
Conditional Statements

switch Statement
The ‘switch‘ statement is useful for checking one variable against multiple
possible values.
Syntax:
1 switch variable
2 case value1
3 % Code for value1
4 case value2
5 % Code for value2
6 otherwise
7 % Code if no match
8 end

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 23 / 36
Conditional Statements

switch Statement
Example:
1 day = ’ Monday ’;
2 switch day
3 case ’ Monday ’
4 disp ( ’ Start of the work week ’) ;
5 case ’ Friday ’
6 disp ( ’ End of the work week ’) ;
7 otherwise
8 disp ( ’Mid - week ’) ;
9 end

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 24 / 36
Loops in MATLAB
Loops allow repeated execution of a block of code based on a condition.
MATLAB provides two types of loops:
for loop: Executes a fixed number of iterations.
while loop: Executes until a specified condition becomes false.
for Loop
The ‘for‘ loop is used for a fixed number of iterations. It is ideal when you
know in advance how many times you want to execute a statement or a block
of statements.
Syntax:
1 for index = startValue : endValue
2 % Code to execute for each value of index
3 end
Example:
1 for i = 1:5
2 disp ( i ) ;
3 end
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 25 / 36
Loops in MATLAB

while Loop
The ‘while‘ loop repeats a block of code as long as a specified condition
remains true. The condition is checked before each iteration.
Syntax:
1 while condition
2 % Code to execute as long as condition is true
3 end

Example:
1 x = 1;
2 while x <= 5
3 disp ( x ) ;
4 x = x + 1;
5 end

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 26 / 36
Branching Statements

The break statements is used to control the flow of loops.


break: Exits the loop immediately.
Example of break:
1 for i = 1:10
2 if i == 6
3 break ; % Exit the loop
4 end
5 disp ( i ) ;
6 end

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 27 / 36
Branching Statements

The continue statement is used to control the flow of loops.


continue: Skips the current iteration and proceeds to the next
iteration of the loop.
Example of continue:
1 for i = 1:5
2 if mod (i , 2) == 0
3 continue ; % Skip even numbers
4 end
5 disp ( i ) ; % Only odd numbers will be
displayed
6 end

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 28 / 36
Exercise

Simple Login System


Write pseudocode for a simple login system that checks a username
and password.

Set a predefined username and password.


Ask the user to input their username and password.
If both values match the predefined ones, display a success
message.
If they do not match, display an error message.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 29 / 36
Exercise

Sum of Even Numbers


Write pseudocode to calculate the sum of all even numbers up to a
given integer, n.

Ask the user to input a positive integer n.


Initialize a variable sum to zero.
Use a loop to iterate from 1 to n.
If the current number is even, add it to sum.
Display the result.
Then, write the MATLAB script.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 30 / 36
Exercise

Simple ATM system


Create a flowchart for a simple ATM system that:
Starts with an initial balance
Allows user to:
Check balance
Deposit money
Withdraw money (if sufficient balance)
Asks if user wants to perform another transaction

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 31 / 36
Exercise

A grading system
Design a flowchart for a grading system that:
Takes marks as input (0-100)
Assigns grades: A (90-100), B (80-89), C (70-79), D (60-69), F
(below 60)
Determines if student passed (grades A-D) or failed (grade F)
Calculates and displays grade point (A=4, B=3, C=2, D=1, F=0)
Then write the MATLAB script.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 32 / 36
Exercise

Sum of Odd Numbers


Write a MATLAB script to calculate the sum of all odd numbers up to
a given number.

Ask the user to input a positive integer, ‘n‘.


Use a ‘while‘ loop to add each odd number from 1 up to ‘n‘.
Display the result after the loop finishes.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 33 / 36
Exercise

Menu Selection
Write a MATLAB script to display a menu and execute different tasks
based on user input.

Display a menu with the following options:


1. Convert Celsius to Fahrenheit
2. Calculate the square of a number
3. Check if a number is even or odd
Use a ‘switch‘ statement to handle each choice:
Option 1: Prompt for Celsius, convert, and display Fahrenheit.
Option 2: Prompt for a number, calculate its square, and display.
Option 3: Prompt for a number, check even/odd, and display result.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 34 / 36
Exercise

Countdown Timer
Write a MATLAB script that creates a countdown timer.

Ask the user to enter a starting number.


Use a ‘while‘ loop to count down to zero.
Display each number in the countdown, then display ”Blast off!”
at the end.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 35 / 36
Exercise

ATM Simulation
Write a MATLAB script to simulate a simple ATM withdrawal
process.

Set a balance, e.g., ‘balance = 500‘.


Ask the user to enter the withdrawal amount.
Use nested ‘if‘ statements to check:
If the amount is less than or equal to the balance, deduct it and
display the new balance.
If the amount exceeds the balance, display ”Insufficient funds.”

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 15, 2024 36 / 36

You might also like