0% found this document useful (0 votes)
6 views38 pages

Control Structures and Programming Paradigms in MATLAB

The document covers programming structures in MATLAB, focusing on control structures, programming paradigms, recursion, dynamic programming, and object-oriented programming. It details various control structures like conditional statements, loops, and event-driven programming, along with their applications and advantages. Additionally, it discusses the characteristics and merits of recursive functions, dynamic programming techniques such as memoization and tabulation, and key concepts in object-oriented programming including classes, inheritance, and encapsulation.

Uploaded by

kintugadafi4
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)
6 views38 pages

Control Structures and Programming Paradigms in MATLAB

The document covers programming structures in MATLAB, focusing on control structures, programming paradigms, recursion, dynamic programming, and object-oriented programming. It details various control structures like conditional statements, loops, and event-driven programming, along with their applications and advantages. Additionally, it discusses the characteristics and merits of recursive functions, dynamic programming techniques such as memoization and tabulation, and key concepts in object-oriented programming including classes, inheritance, and encapsulation.

Uploaded by

kintugadafi4
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

Programming Structures

in MATLAB
MODULE FIVE
Control Structures
Introduction Types and Applications
● Control structures are essential in directing the 1. Conditional Statements (if, elseif, else): Execute code
based on logical conditions.
flow of execution in a program.
2. Switch Statements (switch, case, otherwise): Executing
● Are fundamental building blocks of any one block of code among many alternatives based on
the value of a variable or expression.
programming language
3. Loops
● Facilitate logic implementation and task i. for loop: Repeats a block of code a specified
number of times, iterating over a range of values
repetition as needed
ii. while loop: Repeats a block of code as long as a
● They allow one to; condition remains true.

● make decisions (conditional execution) 4. Control Flow Modifiers


iii. break: Exits the loop prematurely when a
● repeat code (loops) condition is met.
● select between different sections of code iv. continue: Skips the remaining code in the current
iteration of a loop and moves to the next iteration.
based on the program state.
Decision Statements
Nested Decision Statements
For Loops
While Loops
Introduction to Programming paradigms
Programming Paradigms
Overview Applications
● Programming paradigms define the ways in which ● Unstructured programming is simple but
unsuitable for large programs
code is structured, organized, and executed
● Modular programming and Object-Oriented
● Each programming paradigm has its advantages Programs enhance reusability and scalability.
and is suitable for particular types of tasks. ● Recursive programming simplifies code for
problems with a self-similar structure
● Different paradigms have evolved over time to
● Dynamic programming optimizes recursive
address;
solutions for more complex problems.
● Various types of problems
● Functional and declarative programming focus
● Provide different levels of control on expressing the logic of a problem
● Modularity and efficiency ● Event-driven programming responds to real-
time events.
● Understanding these types of programming is
essential for selecting the right approach for a
Types of Programming
Types of Programming
Types of Functions
Types of Functions
Recursive Programming
Characteristics of Recursive
Introduction to Recursion Functions
● A technique where a function calls itself in 1. Base Case: A condition under which the recursion
order to solve smaller instances of the same stops. Without a base case, the recursion would

problem. lead to an infinite loop.

● Each call typically works on a smaller subset of 2. Recursive Case: This is where the function calls

the original problem itself with modified arguments, generally


simplifying the problem in each step.
● Terminates when a base case is reached,
3. Stack Memory Usage: Recursive functions use
where the solution is directly known
stack memory to remember the function calls,
● understanding its types and applications can
leading to a chain of calls until the base case is
greatly enhance problem-solving capabilities in
met. This can sometimes lead to a stack overflow
computational tasks.
if recursion goes too deep without a base case.
Applications of Recursion Merits of Recursion
1. Mathematical Problems: Solving problems 1. Modularity and Reusability: Solutions are often more elegant,
like factorial, Fibonacci, Ackermann function easier to read, maintain and reuse

2. Data Structures: Recursive traversals of data 2. Problem Breakdown: Natural way to model processes
structures like trees and graphs (e.g., depth- involving repetition or self-similarity.
first search, in-order, pre-order, and post-order
3. Real-Time Decision Making: Enhances system
traversals).
responsiveness, accuracy, real-time feedback and
3. Divide and Conquer Algorithms: Sorting adjustments based on changing inputs
algorithms like QuickSort and MergeSort Demerits of Recursion
utilize recursion. 1. Performance: slower due to the overhead of multiple
function calls and the use of stack memory.
4. Dynamic Programming: Recursive solutions
can be optimized using memoization in 1. Stack Overflow: Too deep recursion can lead to stack

dynamic programming. overflow if the base case is not reached quickly or for large
inputs.
5. Combinatorics: Generating combinations and
permutations. 1. Complexity in Debugging: multi-layered function calls can
Types of Recursive Functions
Types of Recursive Functions
Dynamic Programming
Introduction Key Concepts
● An optimization technique used to solve 1. Optimal Substructure: A problem has an optimal
complex problems by breaking them down substructure if its solution can be obtained by solving

into simpler subproblems subproblems and combining their solutions.


This property allows us to recursively define a problem in
● Stores the results of these subproblems to
terms of its subproblems.
avoid redundant computations.
2. Overlapping Subproblems: Many DP problems involve
● Optimizes recursion through storage and
solving the same subproblem multiple times.
reuse results of subproblems thus avoiding
Instead of recalculating the result every time, dynamic
redundant computations.
programming stores these results to avoid redundant
● Is effective when a problem exhibits An calculations.

Optimal Substructure and Overlapping 3. Implemented through either Memoization (Top-down


Subproblems approach) or Tabulation (Bottom-up approach)
Memoization (Top-Down Dynamic Programming)
● Memoization involves solving the problem recursively and storing the result of each subproblem in a cache
(a data structure like a table, dictionary, or array).

● This technique starts with the original problem and works its way down to smaller subproblems.

● Once a subproblem is solved, its result is stored to be reused in the future.

Steps in Memoization Advantages: Ideal for problems with large inputs where only a
few subproblems are necessary.
1. Start with the original problem and solve
it recursively. Only computes the necessary subproblems, leading to potential
savings in space and time when only a portion of the DP table
2. Check if the current subproblem has
is needed.
been solved before (cached).

3. If the result is cached, return it. Disadvantages: Recursive nature may cause high memory
usage (stack space) due to deep recursion.
4. If not, compute the result, store it in the
cache, and return the result. Can be slower due to the overhead of recursive function calls.
Tabulation (Down-Up Dynamic Programming)
● Tabulation is an iterative method where the problem is solved by first solving all the smaller subproblems
and storing their results in a table.

● The solution to the original problem is built by using these precomputed results.

Steps in Tabulation Advantages:

1. Start by solving the smallest ● Efficient in both time and space, as it avoids recursion.
subproblem.
● More intuitive for problems where all subproblems need to be
2. Build a table where each entry computed.
corresponds to a subproblem.
Disadvantages:
3. Use the results of previously solved
● Requires solving all subproblems, even those that may not be
subproblems to solve the larger
necessary.
subproblems.
● Larger memory footprint for storing the table, even if some
4. Continue this process until the original
entries are unused.
problem is solved.
Approaches Comparison and DP Applications

Example Applications
1. Fibonacci Numbers: A sequence where each number is the sum of the two preceding ones, starting with 0
and 1.
2. 0/1 Knapsack Problem: Given items with specific weights and values, the goal is to maximize the total value
without exceeding a weight limit.

3. Longest Common Subsequence (LCS): Finds the longest sequence common to two strings.

4. Travelling Salesman Problem (TSP): Finds the shortest route that visits all cities exactly once and returns to
Approaches Syntax
Object-Oriented Programming (OOP)
Overview Key Concepts
● A programming paradigm based on the ● Classes and Objects: Classes are templates, and
objects are instances.
concept of “objects,” which can contain data
● Encapsulation: Data and methods are bundled in
in the form of fields (attributes or properties)
classes; access is controlled.
and code in the form of procedures (methods
● Inheritance: Classes can inherit properties and
or functions). methods from other classes.

● Provides a framework for structuring code in ● Polymorphism: Methods can be overridden in


subclasses to provide specialized behavior.
a way that enhances reusability, scalability,
● Abstraction: Abstract classes define interfaces for
and clarity. subclasses without implementing methods.

● Allows programmers to structure software as ● Handle vs. Value Classes: Handle classes are passed
by reference, while value classes are passed by value
a collection of objects that model real-world
entities and their interactions
Classes and Objects
● Class: A blueprint for creating objects. It
defines a data structure by specifying the
attributes (data) and behaviors (methods) that
the object will have. They are defined with
classdef and saved as .m files

● Object: An instance of a class. An object is a


real entity with properties and behaviors
defined by its class.
Encapsulation
● Bundling of data (attributes) and methods that operate on the data into
a single unit, or class.

● It restricts access to the inner workings of the object and only exposes
selected methods to interact with the object.

● This promotes data hiding and prevents unauthorized access.

Access Modifiers for Properties or methods:

■ Public: Accessible from anywhere.

■ Private: Accessible only within the class.

■ Protected: Accessible within the class and its subclasses.


Inheritance
● A mechanism by which one class (child or subclass) inherits
properties and methods from another class (parent or
superclass).

● This promotes code reuse and establishes a hierarchical


relationship between classes..

Types of Inheritance:

■ Single Inheritance: A class inherits from one superclass.

■ Multiple Inheritance: A class inherits from more than one


superclass.

■ Multilevel Inheritance: A class inherits from a class, which is


itself a subclass.

■ Hierarchical Inheritance: Multiple subclasses inherit from the


same superclass.
Polymorphism
● The ability to define a method in the child class that has the
same name as a method in the parent class but behaves
differently.

● Allows methods to be defined in multiple forms.

● Inherited methods from parent classes can be overridden or


overloaded to provide specific implementations in child
classes.

Polymorphism can be achieved through:

● Method Overloading: Same method name but different


parameters

● Method Overriding: A child class provides a specific


implementation of a method that is already defined in the
parent class.
Abstraction
● Hides the complexity of
implementation details and
exposing only the essential
features of a class.

● Achieved by using abstract


classes and interfaces (methods)

● Used to define a common


interface or methods for
subclasses without
implementing specific
functionality.

● An abstract class is a class that


cannot be instantiated directly
Handle vs. Value
Classes
● Value Classes: Objects of value classes
behave like standard variables (they are
copied when passed).

● Handle Classes: Objects of handle classes


are passed by reference, allowing changes
to the object within a function to persist
outside of the function.

● Handle classes are passed by reference,


while value classes are passed by value.

● You define a handle class by inheriting from


the handle class
Event-Driven Programming
Overview Key Concepts
● A programming paradigm where the flow of the program is determined ● Event: An action or occurrence detected
by events—user actions (such as mouse clicks or key presses), sensor by the program, such as clicking a button,
outputs, or messages from other programs. typing on a keyboard, or receiving data

● Unlike procedural programming, which follows a fixed sequence of from a sensor.

instructions, event-driven programs react to specific events and execute ● Event Listener: A mechanism that waits
corresponding functions (event handlers). for an event to occur and triggers a

● Widely used in: corresponding event handler.

■ Real-time monitoring systems: Sensors that trigger events for ● Event Handler (Callback Function): A
updates. function executed in response to a

■ Interactive simulations and Graphical user interfaces (GUIs) : User particular event.

interactions trigger changes in simulation parameters. ● Event Loop: A continuous loop in the
■ Automated data acquisition: Asynchronous hardware events program that listens for and dispatches
GUI, Events and Callbacks
GUI Callbacks
● GUIs are built using the App Designer, GUIDE ● Callback functions are executed when specific
(legacy), or through low-level programming with events occur.
UIControl objects and callback functions.
● They are linked to UI components using properties
Common UI components and Applications: like:
■ Buttons: Trigger actions ■ ButtonPushedFcn: for buttons
■ Sliders: Selection of numeric values ■ ValueChangedFcn: for sliders, dropdowns, text and
■ Text Boxes: Text input and display check boxes

■ Dropdown Menus: Select one option from a list ■ KeyPressFcn: for keyboard press events in figure

■ Check Boxes: Enable binary selections (checked/ windows

unchecked) ■ MouseDownFcn: when mouse button is pressed

Timers: For scheduling actions. ● Callback functions can be defined in different ways:
■ Anonymous functions.
Listeners: For monitoring changes in properties.
■ Function handles.
Buttons
● Trigger events
when clicked.

● ButtonPushedFcn
callback is
executed when
the user presses
the button.

● Created using
the uibutton
function (for App
Designer or
uifigure-based
apps) or
uicontrol for
Sliders
● Allows the user to select a numeric value from a continuous or discrete range by moving the slider handle

● Useful for
adjusting
parameters
interactively.

● ValueChangedFcn
callback that is
executed when
the slider is
moved.

● Created using the


uislider function
(for App Designer
or uifigure-based
● Allows the user to input
or display text.
Text Boxes
● They can be single-line
(uitextfield) or multi-line
(uitextarea)

● The ValueChangedFcn
callback is trigged when
the content of the text
box changes.

● Created using the


uitextfield for single-line
or uitextarea function
multi-line (for App
Designer or uifigure-
based apps) or uicontrol
for traditional figures
Dropdown Menus
● Allows the users to select one option from a list of predefined options.

● The ValueChangedFcn callback is triggered when the user selects a new option from the dropdown.

● Created using the uidropdown (for App Designer or uifigure-based apps) or uicontrol for traditional figures
Check Boxes
● Allows the users to
make binary (true/
false) selections.
Useful for enabling
or disabling options.

● The
ValueChangedFcn
callback is triggered
when the checkbox
state changes.

● Created using the


uicheckbox (for App
Designer or uifigure-
based apps) or
uicontrol for
Events, Listeners and
Notifications
● Listeners respond to changes in the value
of a property or the occurrence of an
event.

● It monitors an object for a specific event,


and when that event occurs, a specified
function (callback) is executed.

● The addlistener function is used to add a


listener to an object.

● The notify function is used to trigger an


event from within a class.

● It tells MATLAB that a specific event has


occurred, and any listeners waiting for
this event will execute their callbacks.
Event Loops, Timers and Serial Ports
● The program enters an event loop that continuously waits for events and dispatches them to the appropriate
handlers

● No need to explicitly write a loop as the GUI automatically manages it internally.

● Asynchronous events are triggered using callback functions that interact with hardware (e.g., timers, serial ports)
upon receiving data
Error Handling and Debugging
Introduction Types and Applications
● Are critical skills in programming that enable developers to write robust, Types of Errors:
maintainable, and fault-tolerant code.
● Syntax Errors: Code cannot be interpreted
● Error handling: ensures that the program gracefully manages unexpected due to incorrect use of the language.
conditions Caused by missing parentheses,
unrecognized variables, or improper
● Debugging: allows for identifying and resolving coding issues.
command usage.
Best Practices for Error Handling and Debugging:
■ Write Modular Code: Split your code into small functions and test each ● Runtime Errors: Occur when an
individually. operation is invalid during execution.
Such as division by zero or
■ Use Meaningful Error Messages: Provide informative error and warning
messages to facilitate debugging. referencing a non-existent element in
an array.
■ Log Errors: Keep a log of errors that occur during execution for troubleshooting.
● Logical Errors: Don’t cause the
■ Use try-catch Appropriately: Avoid overuse; handle only specific, expected errors.
program to fail or throw an error but
■ Automate Tests: Develop unit tests using MATLAB’s unittest framework
Error Handling and Debugging
Introduction Best Practices
● Are critical skills in programming that enable developers to write ■ Write Modular Code: Split your code into
robust, maintainable, and fault-tolerant code. small functions and test each individually.

● Error handling: ensures that the program gracefully manages ■ Use Meaningful Error Messages: Provide
unexpected conditions informative error and warning messages
to facilitate debugging.
● Debugging: allows for identifying and resolving coding issues.

Types of Errors: ■ Log Errors: Keep a log of errors that occur


● Syntax Errors: Code cannot be interpreted due to incorrect use of during execution for troubleshooting.
the language. (missing parentheses, unrecognized variables, or ■ Use try-catch Appropriately: Avoid
improper command usage) overuse; handle only specific, expected
● Runtime Errors: Occur when an operation is invalid during execution. errors.
(division by zero or referencing a non-existent element in an array)
■ Automate Tests: Develop unit tests using
● Logical Errors: Don’t cause the program to fail or throw an error but
MATLAB’s unittest framework to
lead to incorrect results. (Often the hardest to detect)
automatically check code correctness.

You might also like