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

Lecture2_Computing

MATlab programming 2

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

Lecture2_Computing

MATlab programming 2

Uploaded by

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

Computing and Software Engineering

GET211

Emmanuel Ali
Ayibaemi Ledum

October 20, 2024

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 1 / 23


Outline

1 Introduction

2 Introduction to MATLAB

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 2 / 23


MATLAB

MATLAB (MATrix LABoratory) is a high-level programming language


and numerical computing environment developed by MathWorks. It’s
widely used in various fields including engineering, scientific computing,
signal processing, image processing, control systems, and more.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 3 / 23


Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 4 / 23
MATLAB environment and interface

Desktop Layout
The MATLAB desktop is highly customizable, allowing users to arrange
various tools and windows according to their preferences.
It typically includes the Command Window, Workspace, Current Folder,
and Editor, among other tools.
Command Window
This is the primary interface for entering commands and executing
MATLAB code interactively.
It displays the MATLAB prompt (>>) where users can type commands
directly.
Results of computations are immediately displayed here.
It also shows error messages and warnings.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 5 / 23


MATLAB environment and interface
Workspace Browser
Displays all variables currently in memory, along with their size, type,
and other properties.
Allows users to view and manipulate variable contents.
Provides a quick way to import, export, or clear variables.
Current Folder Browser
Shows the contents of the current working directory.
Allows navigation through the file system.
Provides quick access to MATLAB scripts, functions, and data files.
Editor
A full-featured text editor for creating and modifying MATLAB scripts
(.m files) and functions.
Includes syntax highlighting, code folding, and auto-completion features.
Integrated debugging tools for finding and fixing errors in code.
Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 6 / 23
MATLAB environment and interface
Figure Window
Displays graphical output from plotting commands.
Includes tools for manipulating and annotating plots.
Help Browser
Provides comprehensive documentation for MATLAB functions and
features.
Includes examples, syntax information, and related functions.
Toolstrip
A ribbon-like interface at the top of the MATLAB desktop.
Provides quick access to commonly used functions and tools.
Command History
Keeps a record of previously executed commands.
Allows easy reuse of past commands.
Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 7 / 23
Variables
A variable is a storage location identified by a name (or identifier) that holds
a value, which can be of various types (e.g., numbers, strings, arrays). In
essence, variables provide a way to label and store data that can be retrieved,
modified, and used throughout a program.
Unlike some programming languages, MATLAB is dynamically typed,
meaning you don’t need to declare the type of a variable explicitly. The type
is determined automatically when you assign a value to the variable.

Characteristics of Variables:
- Named Storage Location: Each variable has a unique name (identifier),
which is used to access the stored value.
- Data Type: Variables can store different types of data (integers,
floating-point numbers, characters, etc.).
- Mutable: Variables can change value over time during the execution of a
program.
- Scope: Variables have a defined region (scope) where they can be accessed.
This can be local (within a function) or global (across the entire program).
- Lifetime: A variable’s lifetime refers to the period during which the variable
exists in memory (from its creation to its destruction).
Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 8 / 23
Variable Declaration and Assignment

In MATLAB, you create a variable simply by assigning a value to it:


1 x = 5;
2 name = ’ Alice ’;

MATLAB uses the = operator for assignment. The variable name is on


the left, and the value is on the right.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 9 / 23


Variable Naming Conventions
Variable naming conventions are a set of rules and guidelines followed by
programmers to name variables in a readable, maintainable, and error-free
manner. Consistent naming conventions make the code more understandable,
especially when collaborating with others or when revisiting code after some
time.
The following are the general rules for variable naming:
- Start with a Letter: Variable names must begin with a letter (upper or
lower case) or an underscore ( ), followed by letters, numbers, or underscores.
1 myVariable , _variable1 % Correct naming
2 1 variable , # var % Incorrect naming
- No Spaces: Spaces are not allowed in variable names. Instead,
programmers use underscores (‘‘) or camelCase (more on this later).
1 my_variable , myVariable % Correct naming
2 my variable % % Incorrect naming
- Case Sensitivity: Variable names are often case-sensitive, meaning myV ar
and myvar are considered two different variables.
1 x = 10; % Assigns 10 to variable x
2 X = 20; % Assigns 20 to a different variable X
Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 10 / 23
- No Reserved Words: Variable names should not use keywords or reserved
words in the programming language, such as ‘if‘, ‘for‘, or ‘while‘.
1 % Reserved words such as ‘ while ‘ cannot be used
as variable names
2 whileVar = 10; % Correct

- Meaningful Names: Variables should have descriptive names that indicate


the role or value they represent. Avoid single-letter names (except in loop
counters or short, local variables).
1 radius = 5; % Good variable name
2 r = 5; % Not descriptive

Use Descriptive Names


- Variables should have names that clearly describe what they represent. This
makes the code more readable and maintainable.
Good Bad

1 principalAmount = 1000; 1 a = 1000;


2 interestRate = 0.05; 2 b = 0.05;

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 11 / 23


Avoid Single-letter Variable Names
Single-letter names like ‘x‘, ‘y‘, or ‘i‘ should be avoided unless used in very
simple loops or for common mathematical concepts.
Bad Good

1 i = 10; 1 index = 10;

Short but Descriptive for Loop Variables


In loops or short scopes, it’s common to use short variable names like ‘i‘, ‘j‘,
‘k‘ for counters or indices.
1 for i = 1:10
2 disp ( i ) ;
3 end
Use Consistent Naming Conventions
Stick to one naming convention throughout the program for consistency.
Avoid mixing camelCase and snake case in the same program.
Consistent Inconsistent

1 numStudents = 100; 1 num_students = 100;


2 totalScore = 85; 2 TotalScore = 85;

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 12 / 23


Common Naming Conventions
Different programming languages and communities have specific conventions for naming variables. While
the specific rules vary, there are some widely used naming styles:
Camel Case (camelCase): In camelCase, the first word is lowercase, and subsequent words are
capitalized with no spaces between them. Often used in variable names.

1 myVariableName
2 totalSum
Pascal Case (PascalCase): Similar to camelCase, but the first letter of every word (including the first
word) is capitalized. Often used for naming classes

1 MyVariableName
2 TotalSum
Snake Case (snake case): In snake case, all letters are lowercase, and words are separated by
underscores. Often used in variable names.

1 my_variable_name
2 total_sum
Uppercase with Underscores (UPPER CASE:) All letters are uppercase, and words are separated
by underscores. This convention is often used for constants.

MAX VALUE
PI CONSTANT

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 13 / 23


Special Variables in MATLAB

Variable Description Example


ans The default variable where 2 + 2;
the result of an operation is disp(ans);
stored if no other variable is % Displays 4
specified. Stores the result of
the most recent calculation.
pi A predefined constant repre- area = pi * r^2;
senting the value of (3.1416).
i/j Represent the imaginary unit z = 3 + 4i;
in complex numbers. % Complex number 3
+ 4i
inf Represents infinity. Used for x = 1 / 0;
values too large to represent. % Results in inf
NaN Represents ”Not-a-Number”, result = 0/0;
used for undefined or unrep- % This will return NaN
resentable numeric results.
Table 1: Special Variables in MATLAB

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 14 / 23


Variable Scope
Workspace Variables
Variables created in the MATLAB command window or in scripts are stored
in the base workspace.
Local Variables
Variables created inside a function are local to that function.
Global Variables
Declared with the ‘global‘ keyword, accessible across different functions and
scripts:
1 global shared_var ;
2 shared_var = 100;
Persistent Variables
Retain their values between function calls but are only accessible within the
function:
f u n c t i o n count = c o u n t e r ( )
persistent n
i f isempty ( n )
n = 0;
end
n = n + 1;
count = n ;
end
Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 15 / 23
Variable Information and Management

Checking Variables
- who: List variables in the workspace.
- whos: Provides a detailed list of variables, including type and size
information.
- exist(’varname’, ’var’): Checks if a variable with the name ’varname’
exists in the workspace.

Clearing Variables
- clear x: Clears the specific variable ‘x‘ from the workspace.
- clear: Clears all variables from the workspace.
- clearvars: Provides more flexibility in clearing variables by name or
pattern.
- clc: Clears the Command Window but does not affect workspace
variables.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 16 / 23


Exercise

Create descriptive variable names for the following concepts. Consider


clarity and maintainability.
The total number of students in a class
The average score of students
The current temperature in Celsius
The maximum value in a dataset
A flag indicating whether the data is valid (true/false)

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 17 / 23


Exercise

Create three variables in MATLAB:


- Assign the value ‘10‘ to a variable named ‘a‘.
- Assign the value ‘5.5‘ to a variable named ‘b‘.
- Assign the string ‘”MATLAB”‘ to a variable named ‘c‘.
- Then, use the ‘disp‘ function to display each variable’s value.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 18 / 23


Exercise

- Create two variables:


- x with a value of 15
- y with a value of 4
- Using these variables, perform the following operations and store the
results in separate variables:
- Sum of x and y
- Difference between x and y
- Product of x and y
- Quotient of x divided by y
- Display each result using the ‘disp‘ function.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 19 / 23


Exercise

Create two variables:


- a with a value of 5
- b with a value of 10
- Swap the values of a and b so that a becomes 10 and b becomes 5.
- Display the new values of a and b after swapping.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 20 / 23


Exercise

Create a variable called ‘total‘ with an initial value of ‘50‘.


- Update ‘total‘ by adding ‘20‘ to its current value.
- Then, update ‘total‘ again by multiplying it by ‘2‘.
- Display the final value of ‘total‘.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 21 / 23


Exercise

Create two variables:


- ‘length‘ with a value of ‘10‘
- ‘width‘ with a value of ‘5‘

Use these variables to:


- Calculate the area of a rectangle and store it in a variable ‘area‘ (use
the formula ‘area = length * width‘).
- Calculate the perimeter of the rectangle and store it in a variable
‘perimeter‘ (use the formula ‘perimeter = 2 * (length + width)‘).
- Display the values of ‘area‘ and ‘perimeter‘.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 22 / 23


Exercise

- Define a constant value ‘piValue = 3.1416‘ to represent the value of π.


- Define a variable ‘radius‘ with a value of ‘7‘.
- Calculate the circumference of a circle using the formula
‘circumference = 2 * piValue * radius‘ and store the result in a variable
‘circumference‘.
- Display the value of ‘circumference‘.

Emmanuel Ali, Ayibaemi Ledum 1st Semester October 20, 2024 23 / 23

You might also like