M-3 Matlab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Functions

• A function is a group of statements that together perform a task. In


MATLAB, functions are defined in separate files. The name of the file
and of the function should be the same.

• Functions operate on variables within their own workspace, which is


also called the local workspace, separate from the workspace you
access at the MATLAB command prompt which is called the base
workspace.

• Functions can accept more than one input arguments and may return
more than one output arguments.
Functions
• It is an M-file(having extension .m) like a script file(using editor
window)
• The variables in the function file are all local.

16-10-2024 © Dr. Gaurav Kumar 2


Types of Function
• User defined function
• Function functions
• Special type of the functions
• Subfunctions
• Private functions
• Nested functions
• Anonymous functions
User-defined function
• It is a MATLAB program that is created by the user,
• saved as a function file
• used like a built-in function
• The function can be
• a simple single mathematical expression
• a complicated and involved series of calculations
• The first executable line in a function file must be the
function definition line Otherwise, the file is considered a
Function Definition Line script file.
• Defines the file as a function file
• Defines the name of the function
• Defines the number and order of the input and output
arguments
Features
a. “%” : it starts the comment line and may be put anywhere in a
program.
b. Anything after “%” is ignored by the MATLAB as a non-
executable statement.
c. A single-output variable is not required to be enclosed in square
brackets [] in the function definition line, but multiple output
variables must be enclosed within [] .

16-10-2024 © Dr. Gaurav Kumar 7


Simple Arithmetic Function:

• function result = add_numbers(a, b)


% This function adds two numbers and returns the result.
result = a + b;
• end
Usage:
sum = add_numbers(5, 3);
disp(sum); % Displays the result.

16-10-2024 © Dr. Gaurav Kumar 8


Area of a circle
• function area = circle_area(radius)
% This function calculates the area of a circle.
area = pi * radius^2;
• end
• Usage
• r = 4;
• circle_area = circle_area(r);
• disp(circle_area);

16-10-2024 © Dr. Gaurav Kumar 9


Matrix Multiplication:
• function result = matrix_multiply(A, B)
• % This function performs matrix multiplication.
• result = A * B;
• end
Usage
A = [1, 2; 3, 4]; % First matrix
B = [5, 6; 7, 8]; % Second matrix
product = matrix_multiply(A, B); % Calls the function to multiply
matrices.
disp(product); % Displays the result.
16-10-2024 © Dr. Gaurav Kumar 10
Some examples
• Calculate the Area of a Rectangle
• Convert Celsius to Fahrenheit
• Check if a Number is Even

16-10-2024 © Dr. Gaurav Kumar 11


• function area = calculate_rectangle_area(length, width)
% This function calculates the area of a rectangle.
area = length * width;
• end
• function fahrenheit = celsius_to_fahrenheit(celsius)
% This function converts a temperature in Celsius to Fahrenheit.
fahrenheit = (celsius * 9/5) + 32;
• end
• function is_even = is_even_number(number)
• % This function checks if a number is even
• is_even = mod(number, 2) == 0;
• end

16-10-2024 © Dr. Gaurav Kumar 12


Other Type of the functions
• Anonymous function
• Function functions
• Subfunctions
• Private functions
Anonymous function

• An anonymous function is a simple (one-line) user-defined


function
• Defined without creating a separate function file (m-file)
• Can be constructed in the Command Window, within a script file,
or inside a regular user-defined function

16-10-2024 © Dr. Gaurav Kumar 14


• See this example

cube = @ (x) x^3

circle = @ (x,y) 16*x^2+9*y^2.

16-10-2024 © Dr. Gaurav Kumar 15


Example
2
𝑒𝑥
• Define the anonymous function f(x)= in the command window
𝑥 2 +5
• FA = @ (x) exp(x^2)/sqrt(x^2+5)
• FA =
@(x)exp(x^2)/sqrt(x^2+5)
The function can then be used for different values of x.
>> FA(2)
ans = 18.1994
>> z = FA(3)
z = 2.1656e+003

16-10-2024 © Dr. Gaurav Kumar 16


If x is an array
• Consider 𝑥 is an array, with the function calculated for each
element, then the function must be modified for element-by-
element calculations
• >> FA = @ (x) exp(x.^2)./sqrt(x.^2+5)
FA = @(x)exp(x.^2)./sqrt(x.^2+5)

>> FA([1 0.5 2])

ans = 1.1097 0.5604 18.1994


16-10-2024 © Dr. Gaurav Kumar 17
More than one variable
• 𝑓 𝑥, 𝑦 = 𝑥 2 − 4𝑥𝑦 + 𝑦 2
>> HA = @ (x,y) 2*x^2 - 4*x*y + y^2

HA = @(x,y)2*x^2-4*x*y+y^2

>>HA(2,3)

ans = -7

16-10-2024 © Dr. Gaurav Kumar 18


Function Functions
• Function functions are the functions which includes name of the
other function in its input argument
function y = cubicPoly(x)
y = x.^3 + x.^2 + x + 1;
end
m = @cubicPoly
q = integral(@cubicPoly,0,1)
or
q = integral(m,0,1)
Subfunctions
• In MATLAB, subfunctions are used for encapsulating and
organizing code within a main function

16-10-2024 © Dr. Gaurav Kumar 20


Subfunctions

• Subfunctions are functions defined within the same M-file as the


main function, but they are not directly accessible from outside the
main function
• Cannot access variables defined in the main function
• Useful for breaking down complex tasks into smaller independent
tasks
• More manageable functions and keeping the code organized
• Subfunctions cannot be called or tested independently; they are
only accessible from the main function

16-10-2024 © Dr. Gaurav Kumar 21


• % Main function

function mainAdder()
a = 5;
b = 7;
result = subFunction(a, b);
disp(['Result: ' num2str(result)]);
end
• % Subfunction
function c = subFunction(x, y)
c = x + y;
end

• % Call the main function


mainAdder()

16-10-2024 © Dr. Gaurav Kumar 22


16-10-2024 © Dr. Gaurav Kumar 23
Debugging
• Identifying and fixing errors or defects in software, hardware, or
other systems
• It is an essential part of the software development and
maintenance cycle, where programmers or developers seek to
eliminate problems, also known as "bugs," that cause the system to
behave incorrectly or unexpectedly

16-10-2024 © Dr. Gaurav Kumar 24


Possible issues for debugging
• Program is not running
• Program is partially running and showing error on a particular line
• Program is running but output is incorrect
Program is not running
• Check whether the program is in current directory
• Check the name of the function of file
• Trying to run function without inputs
Program is partially running and showing
error in a particular line
• File not found: Required file is not present in the current directory or on the given
path
Open MATLAB.

Go to the "Home" tab on the MATLAB desktop.

In the "Environment" section, click on "Set Path." This will open the "Set Path"
Preferences window.

In the "Set Path" Preferences window, you can add or remove directories from the
MATLAB path.

Click "Save" to apply the changes and save the path preferences.
Program is partially running and showing
error in a particular line
• Inner matrix dimension must agree : Because of not following the
matrix rules, inner matrix dimension mismatch
• Undefined function or command : Incorrect command or
statement

16-10-2024 © Dr. Gaurav Kumar 28


Iterative statements
• While loops
• for loops
• If-else loop
The while Loop
• Loop is a structure for repeating a calculation(s) a predefined
number of times
• Each repetition of loop is known as pass
• The while loop is used when looping process terminates because the
prescribed condition is met
• Unlike a for loop the number of passes is not known in advance
The general structure

while logical expression


statement(s)
end

16-10-2024 © Dr. Gaurav Kumar 30


Example: while loop
x =2; Initial value

while x <20
x = 3*x – 1
end

• The loop variable must have a value before the


while statement
• This loop variable must be changed by the
MATLAB statements
16-10-2024 © Dr. Gaurav Kumar 31
Example-2
• Write a script file to calculate how long it will take to double an
initial investment of Rs 1000 in an account with an annual rate of
return of 6%.
balance = 1000;
year = 0;
while balance < 2000
year = year +1;
balance = balance*(1+0.6);
end

16-10-2024 © Dr. Gaurav Kumar 32


Example-2(another approach)
i = 1;
balance (1)= 1000;
while balance(i) < 2000
i = i +1;
balance(i) = balance(i+1)*(1+0.6);
end

16-10-2024 © Dr. Gaurav Kumar 33


2. For Loops:
• A for loop is used when number of passes is known in advance

for variable = m:s:n


statements
end

m : initial value
s : step (incremental) value
n : terminating value

16-10-2024 © Dr. Gaurav Kumar 34


For loop : example

for i = 2:2:4
x = i^2
end
fprintf(‘The answer is %d \n’ , x)
m:2
s :2
n:4

16-10-2024 © Dr. Gaurav Kumar 35


3. If-Else Statements:
• An ‘if’ statement in MATLAB is used to conditionally execute code
based on a specified condition

x = 7;
if x > 5
disp('x is greater than 5');
else
disp('x is not greater than 5');
end

16-10-2024 © Dr. Gaurav Kumar 36


Iteration
statements
elseif: for additional condition

y = 3;
if y > 5
disp('y is greater than 5');
elseif y == 5
disp('y is equal to 5');
else
disp('y is less than 5’);
end

16-10-2024 © Dr. Gaurav Kumar 38


Problems
• Write a MATLAB program to calculate the sum of all even numbers
from 1 to 20 using a while loop.

• Write a MATLAB program to determine if a given number is


positive, negative, or zero using if-else statements.

16-10-2024 © Dr. Gaurav Kumar 39


Solution-1
sum_even = 0;
num = 2;
while num <= 20
sum_even = sum_even + num;
num = num + 2;
end
disp(['The sum of even numbers from 1 to 20 is: '
num2str(sum_even)]);

16-10-2024 © Dr. Gaurav Kumar 40


Solution-2
num = -10; % Change 'num' to any number you want to check

if num > 0
disp([num2str(num) ' is a positive number.']);
elseif num < 0
disp([num2str(num) ' is a negative number.']);
else
disp([num2str(num) ' is zero.']);
end

16-10-2024 © Dr. Gaurav Kumar 41


Top-down design approach

Determine the
Design the
Start State the problem number of input
algorithm
and outputs

Convert the
Test the output of
algorithm into
the MATLAB Finish
MATLAB
Program
statements
Top –Down Design Techniques
• An algorithm is a step-by-step procedure for finding the solution of a
problem
• The standard forms that we used to describe algorithms are called
constructs
• These constructs are also known as pseudo codes (p-codes)
• P codes are the hybrid mixture of MATLAB and English
• Separate line is written for each distinct idea or segment
Pseudocode
Example: Write pseudocode for a MATLAB program which converts
temperature from degree Fahrenheit to Kelvins.
Prompt the user to enter temperature in degree Fahrenheit

Read temperature in degree Fahrenheit (TF)

Temperature in Kelvin (TK)----→ (5/9)* (TF-32) + 273.15

Write temperature in Kelvin

You might also like