User Functions
User Functions
Lab
Matlab Language
User Functions in MATLAB
ALI ABDULRAZZAQ ABDALI
User Functions in MATLAB
● User-defined functions are custom-written code that can be used to perform a
specific task.
● They can be used to improve code reuse, organization, and performance.
● User-defined functions are defined using the function keyword.
● They consist of a function statement, variable declarations, and a function body.
● User-defined functions are called using the call keyword.
● It should be noted that when storing a file (M-file) that contains a function, its name
must be similar to the name of the function itself
Example 1
Write a program to add two numbers using When executed, it is written in the
matlab in function defined User command window
1- open the file (mfile) Call the function and it's like this
s = sums(4, 6);
end s = 10
Notes :
User-defined functions can have any number of arguments.
A function file that was recently stored can be called in any other program
How to find the area and circumference of a circle
In this example,use a user-defined function function [A,C] = area_circum (R)
to find the area and circumference of a A = pi * R^2;
circle. The function takes one argument, R, C = 2 * pi * R;
which is the radius of the circle. The
end
function body uses the following equations
to calculate the area and circumference: [A,C] = area_circum(4);
The function takes three arguments, x, y, and z, which are the grades.
The function body uses the following code to calculate the sum and average of the grades:
s = x + y + z;
av = s / 3;
The function returns two variables, s and av, which are the sum and average of the grades,
respectively.
Example
In this example, we will use two files, one for The second file is as follows:
the function and one for reading the grades
and calling the function.
x = input('input x ');
y = input('input y');
The function file is as follows:
z = input('input z');
function [s,av] = avg_sum(x, y, z)
[s, av] = avg_sum(x, y, z);
s = x + y + z;
disp(['s = ' num2str(s)]);
av = s / 3; disp(['av = ' num2str(av)]);
end
Thank you for attention