0% found this document useful (0 votes)
15 views8 pages

TP N°6

Uploaded by

foufita24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views8 pages

TP N°6

Uploaded by

foufita24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

People's Democratic Republic of Algeria

Ministry of Higher Education and


Scientific Research
Mohamed Chérif Messaâdia University –Souk Ahras
Faculty of Science and Technology

TP N° 06: Function file


[email protected]

College year: 2024-2025

1
Introduction
• Functions are blocks of reusable and organized code that
usually perform a single, related action.
• They are a crucial part of programming because they save
you a lot of time and make your code cleaner.
• Once a function is defined, it can be used over and over
and over again.

2
1. Write a function in Matlab
• To write a function in Matlab, the first rule to follow is to give the .m
file the same name as the function you are writing. For example, a
function called mafact must be written in the file mafact.m.
• To write a function in Matlab, we must first give the names of the
output values ​generated by the function, then the name of the
function, and finally the names of the input parameters of the function:
• In Matlab click new -> Function
• A prototype is given as follows:
• function [output1,output2, ...] = name_fonction(args1,args2, ...)
• ... end
3
1. Write a function in Matlab
• Example:
• For example, if we want to make a product function, which
calculates and returns as output the product of two
scalars passed as a parameter, we will write in the file
product.m:
• function [res] = product(a,b)
res = a*b;
• end 4
1. Write a function in Matlab
• To test this function, place in the directory that contains
the file product.m and write in the command window:
• e = produit(2,4);
• Once this command is executed, we recover in e the
output value of the function, that is to say the product of
the two input parameters

5
1. Write a function in Matlab
• Exercice 01:
• Write in Matlab a function named increment that
increments a number ?
• In command window call this function with the number 5
• Exercice 02:
• Write a function that takes a matrix as a parameter, and
returns as output the maximum element of this matrix.
6
2. Transform the script into
function
• To transform the script into function see the following
example:
• a= input(‘give a’)
• b=input(‘give b’)
• S= a+b
• Disp (‘a+b =%d‘, s);

7
2. Transform the script into
function
Function [s]= sum(a,b)
s= a+b
End
In the script we call it:
• a= input(‘give a’)
• b=input(‘give b’)
r=sum(a,b)
• Disp (‘a+b =%d‘, r);
8

You might also like