Is it possible to set a function within one m file and use that function in matlab?

In Python, we can set a function and use function at a same file.
then,Is it possible to set a function within one m file and use that function in matlab?
for example, i want to make summantion function like this,
clear all; close all; clc
N1=1; N2=100;
function summation(N1,N2)
x=0;
for ct=N1:N2
x=x+ct;
end
end
summation(N1,N2)

 Accepted Answer

Yes. The function definition must be after the script calling it, and the name of the script cannot be the same as the name of the function.

5 Comments

Thank you for your answer
so.. you mean that is impossible.. right?
"so.. you mean that is impossible.. right?"
Your original question was "Is it possible to set a function within one m file and use that function in matlab? " and Walter Roberson answered "Yes".
In any case, the best place to learn about MATLAB is by reading the documentation:
clear all; close all; clc
N1=1; N2=100;
summation(N1,N2)
function summation(N1,N2)
x=0;
for ct=N1:N2
x=x+ct;
end
end
stored in a file that is not named summation.m
What is not possible in MATLAB is a function definition in the middle of a script. It is possible to define a function in the middle of a function.
function drive_my_car
N1=1; N2=100;
function summation(N1,N2)
x=0;
for ct=N1:N2
x=x+ct;
end
end
summation(N1,N2)
end
Thanks for your answer.
Now i can understand everything.
In python, The function definition must be before the script calling it so i confused.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!