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

University of Salahaddin-Hawler

College of Engineering
Software and Informatics Engineering Department
Second Year Class

Numerical Analysis
and
Probability

M Function

Lecturer
Kanar Shukr Muhamad

2023-2024
Function
 Functions let you do a specific task. User defined functions

are the functions created by the users according to their


needs.

 MATLAB permits creating own functions

 These are scripts that take in certain inputs and return a

value or set of values

2
Function
 Declaration function

 function output(return value)=function_Name(input(s))

 Functions’ body …..

 End

 For saving a user defined function, go to Home -> New

Scripts, write the function definition and save the script as


the function name.

3
Function
After writing the function and saving the file as
the function name, write the function name and
gives value(s) to its parameter call and execute the
function in the command window.

4
Function
Ac12: Write a M function that takes a number and return sqrt of
it.

5
Activities
 Ac13/ Write a M function that takes a number, return sqrt

and power two of it.

 Ac14/ Write a MATLAB function that takes

coordinate of two points: A and B (in a


plane), and then displays the distance
between them.
6
Sub Function

Sub functions allow us to put two functions in


one file. Use this to consolidate files into one
file.

7
Activities
 Ac15/ Write a function named quadratic that would

calculate the roots of a quadratic equation. The function


would take three inputs, the quadratic co-efficient, the
linear co-efficient and the constant term. It would return
the roots, call it in another function.

 Ex/ 5x2 + 6x + 1 = 0 r1=??? r2=????


Note:
r1=(-b-sqrt(b^2-4*a*c))/(2*5);
8
r2=(-b+sqrt(b^2-4*a*c))/(2*5);
Activities
Ac15/ Sol
function [r1,r2]=mFunction()
[r1,r2]=sub(5,6,1); %call sub function
end

function [r1,r2]=sub(a,b,c)
r1=(-b-sqrt(b^2-4*a*c))/(2*5);
r2=(-b+sqrt(b^2-4*a*c))/(2*5);
end

You might also like