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

Lecture4_Computing

MATlab programming 3

Uploaded by

AMDCrafto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture4_Computing

MATlab programming 3

Uploaded by

AMDCrafto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Computing and Software Engineering

GET211

Emmanuel Ali
Ayibaemi Ledum Jaafaru Sanusi

November 3, 2024

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 1 / 28
Outline

1 Introduction

2 Introduction to MATLAB

3 Data Type

4 Inputs and Outputs

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 2 / 28
Components of a Program

We provide a conceptual walkthrough of various aspects specifically on


MATLAB, and guidance on how MATLAB program components and
workflows fit together. This structure can help you understand
MATLAB programming principles from foundational elements to
advanced concepts.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 3 / 28
MATLAB Program Components

This overview serves as a foundation for understanding MATLAB’s


components and their roles in program development. It outlines the the key
components in MATLAB program development.
The diagram here organizes MATLAB programming elements into categories:
- Basic Structure: Covers the foundational elements like Scripts, Functions,
and Classes.
- Data Types: Lists the core data types used in MATLAB, including
Numeric, Character, and Structures.
- Control Flow: Explains constructs like Loops, Conditionals, and Error
Handling** that control the execution flow.
- I/O Operations: Introduces File I/O, User I/O, and Graphics, which are
essential for interacting with users and external files.
- Advanced Features: Covers advanced programming aspects like
Object-Oriented Programming (OOP), Toolboxes, and MEX Files for
extending MATLAB’s functionality.
- Program Organization: Includes Documentation, Testing, and Version
Control, which are vital for maintaining and scaling code.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 4 / 28
MATLAB
Program
Components

Basic Data Control I/O Advanced Program


Structure Types Flow Operations Features Organization

Error Version
Scripts Functions Classes Numeric Character Structures Loops Conditionals Handling File I/O User I/O Graphics OOP Toolboxes MEX DocumentationTesting
Control

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 5 / 28
Program Hierarchy and Data Flow

We illustrate the hierarchical structure of a MATLAB program and


how data flows between components.
The main structure begins with the program, which serve as entry
points to run code.
- Scripts, Functions, and Classes are organized as the types of program,
each with specific roles:
- Scripts handle Data Processing and Visualization.
- Functions can be either Built-in or User-defined, providing reusable
code blocks.
- Classes are organized into Properties and Methods, encapsulating
data and behaviors.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 6 / 28
Program Hierarchy and Data Flow

Main Program

Scripts Functions Classes

Data Built-in User-defined


Visualization Properties Methods
Processing Functions Functions

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 7 / 28
Data Flow and Component Interaction

We describe the data flow among MATLAB components and highlight the
interactions between key system components.
Data Flow Section:
- The Input Components receive data, which is passed to Processing
Components for analysis or transformation.
- Processed results are sent to Output Components for display or further
action, and saved to Data Storage Components if needed.
- Stored data can be reloaded and used in subsequent operations, showing the
cyclical nature of data flow in a MATLAB program.

Component Interaction Section:


A Core System interacts with various subsystems:
- I/O Interface handles input/output.
- Data Management processes data.
- Control Flow directs the execution order.
- Storage System manages saved data.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 8 / 28
Data Flow and Component Interaction

Data Results
Input Processing Output
Components Components Components

Save
Load

I/OInterface DataManagement Data


Storage
Components
Input
Process

Flow CoreSystem Save

Control Store

ControlFlow StorageSystem

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 9 / 28
Program Development Lifecycle

We provide an overview of a program development lifecycle, highlighting


phases and essential activities. We emphasizes the two main stages of program
development and the importance of proper organization, documentation, and
resource management to ensure robust program execution.
Development Phase:
Encompasses activities related to coding and documenting:
- Source Code Management includes handling Scripts, Functions, and Classes,
organizing code into reusable components.
- Documentation Process covers Comments, Help Files, and User Guides to
ensure clear communication about program functionality.
Execution Phase:
Focuses on the runtime environment and data management:
- Runtime Environment ensures efficient Memory Management, Process
Control, and Error Handling during execution.
- I/O Management involves Input Processing, Data Storage, and Output
Generation, enabling interaction with data during execution.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 10 / 28
Program Development Lifecycle

Program
Development

Development Execution
Phase Phase

Source Code Documentation Runtime I/O


Management Process Environment Management

Memory Process Error Input Data Output


Scripts Functions Classes Comments Help Files User Guides
Management Control Handling Processing Storage Generation

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 11 / 28
Command Window Input

Inputs are essential for interactive programming, enabling users to provide


data that influences the execution of scripts and functions.
User Input
User input can be captured interactively from the command line using the
input function. This allows users to provide numerical or string values while
the program is running.
Numerical Input To prompt the user for a number, you can use the input
function without any additional parameters.
1 num = input ( ’ Enter ␣ a ␣ number : ␣ ’) ; % User enters a
number

String Input To prompt for a string, you can specify the second argument as
’s’.
1 name = input ( ’ Enter ␣ your ␣ name : ␣ ’ , ’s ’) ; % User
enters a string

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 12 / 28
Command Window Output

Outputs in MATLAB refer to the results produced by scripts and


functions after executing code. This section provides an overview of
various methods for displaying outputs, including command window
outputs, returning values from functions, and exporting data to files.
Displaying Outputs
The most common way to display outputs in MATLAB is through the
command window. You can use several functions to show results to the
user.
Using disp
The disp function displays a message or variable value without
printing the variable name.
1 result = 10 * 5; % Perform a calculation
2 disp ( result ) ; % Display the result

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 13 / 28
Command Window Output
Using fprintf
The fprintf function provides formatted output, allowing you to control the
appearance of the output text.
1 name = ’ Alice ’;
2 age = 30;
3 fprintf ( ’ Name : ␣ %s , ␣ Age : ␣ % d \ n ’ , name , age ) ; %
Formatted output
Using sprintf
The sprintf function formats data into a string without displaying it
immediately. This can be useful for constructing messages that will be
displayed later.
1 outputString = sprintf ( ’ The ␣ result ␣ is : ␣ %.2 f ’ ,
result ) ; % Format as string
2 disp ( outputString ) ;
% Display the formatted string
Escape Characters: Special characters such as \n (newline) and \t (tab) can
be used to format text output.
Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 14 / 28
Exporting Data
MATLAB allows you to export data to various file formats, making it
easier to share results or save them for later use.
Writing to Text Files
You can write data to text files using the writetable or writematrix
functions.
1 data = [1 , 2 , 3; 4 , 5 , 6];
2 writematrix ( data , ’ outputData . csv ’) ; % Write matrix
to CSV file

Writing to Excel Files


MATLAB can also write data directly to Excel files using the
writetable function.
1 T = table ([1; 2] , [3; 4] , ’ VariableNames ’ ,
{ ’ Column1 ’ , ’ Column2 ’ }) ;
2 writetable (T , ’ outputData . xlsx ’) ; % Write table to
Excel file

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 15 / 28
Importing Data

MATLAB can read data from external files, which is useful for processing
datasets or configurations stored outside the workspace.
Reading Text Files
You can use various functions to read data from text files, such as readtable,
readmatrix, and readcell.
Using readtable This function reads data from a text file into a table.
1 data = readtable ( ’ data . csv ’) ; % Read data from a CSV
file

Using readmatrix This function reads numerical data into a matrix.


1 matrixData = readmatrix ( ’ data . csv ’) ; % Read
numerical data from a CSV file

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 16 / 28
Text Files

Writing Text Files


Use fprintf for writing.
1 fid = fopen ( ’ output . txt ’ , ’w ’) ;
2 fprintf ( fid , ’ This ␣ is ␣ a ␣ test .\ n ’) ;
3 fclose ( fid ) ;

‘fopen‘ opens a file, ‘fgets‘ reads a line at a time, and ‘fscanf‘ reads
formatted data.
Use fopen, fgets, fscanf for reading.
1 fid = fopen ( ’ output . txt ’ , ’r ’) ;
2 line = fgets ( fid ) ;
3 disp ( line ) ;
4 fclose ( fid ) ;

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 17 / 28
Binary File I/O

MATLAB supports reading and writing binary files using ‘fopen‘,


‘fread‘, ‘fwrite‘, and ‘fclose‘.
Writing Binary Files
Binary files store data in compact binary format, which can be efficient
for large datasets.
1 fid = fopen ( ’ data . bin ’ , ’w ’) ;
2 fwrite ( fid , magic (3) , ’ double ’) ;
3 fclose ( fid ) ;

Reading Binary Files


You can read binary data from files using fopen and fread.
1 fileID = fopen ( ’ data . bin ’ , ’r ’) ; % Open binary file
for reading
2 binaryData = fread ( fileID ) ; % Read binary data
3 fclose ( fileID ) ; % Close the file

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 18 / 28
CSV Files
CSV (Comma-Separated Values) files are a common format for storing
tabular data.
The csvwrite() function writes numeric data to a CSV file.
1 % Create a 3 x3 magic square matrix
2 M = magic (3) ;
3
4 % Write the matrix to a CSV file
5 csvwrite ( ’ magic . csv ’ , M ) ;

The csvread() function reads numeric data from a CSV file.


1 % Read data from the CSV file
2 N = csvread ( ’ magic . csv ’) ;
3
4 % Display the data
5 disp ( N ) ;

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 19 / 28
Image File

MATLAB provides functions for importing and exporting image files in


various formats (e.g., JPEG, PNG, BMP).
The imread() function reads image data from a file.
1 % Read an image file
2 img = imread ( ’ myimage . jpg ’) ;
3
4 % Display the image
5 imshow ( img ) ;

The imwrite() function writes image data to a file.


1 % Save the image to a new file in PNG format
2 imwrite ( img , ’ newimage . png ’) ;

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 20 / 28
MAT-File I/O
MATLAB’s native file format (‘.mat‘) stores variables in binary format
and is efficient for saving and loading MATLAB variables.
Saving Workspace Variables
You can save all workspace variables to a MAT-file for later use using
the save function.
1 save ( ’ myWorkspace . mat ’) ; % Save all variables to a
. mat file

You can also save particular variables


1 x = 1:10;
2 y = x .^2;
3 save ( ’ mydata . mat ’ , ’x ’ , ’y ’) ;

- Loading Data:
1 load ( ’ myData . mat ’) ;

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 21 / 28
Exercise

Write a MATLAB script that prompts the user to enter their name
and age.
- Use the ‘input‘ function to get this information.
- Display a greeting message that includes the user’s name and age
using the ‘disp‘ function.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 22 / 28
Exercise

Create a script that asks the user to input a temperature in Celsius


and converts it to Fahrenheit.
- Use the formula: F = 95 × C + 32.
- Display both the Celsius and Fahrenheit values in a formatted
message.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 23 / 28
Exercise

Write a script that prompts the user for the radius of a circle and
calculates its area.
- Use the formula: Area = π × r2 .
- Output the area in a formatted string.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 24 / 28
Exercise

Ask the user to enter three numbers.


- Calculate their average and display the result using the ‘fprintf‘
function to format the output.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 25 / 28
Exercise

Create a script that prompts the user to enter five test scores.
- Store these scores in a numeric array and write the array to a CSV
file named ‘tests cores.csv‘.
- Display a message indicating the file has been created.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 26 / 28
Exercise

Write a simple quiz script that asks the user a question (e.g., ”What is
the capital of France?”) and provides multiple-choice answers.
Capture the user’s response using the ‘input‘ function and display it.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 27 / 28
Exercise

Create a script that asks the user for their scores in three subjects.
Calculate the average score and display the score.

Emmanuel Ali, Ayibaemi Ledum, Jaafaru Sanusi 1st Semester November 3, 2024 28 / 28

You might also like