How to create a custom function?
121 views (last 30 days)
Show older comments
Nicole Isbell
on 1 Mar 2014
Commented: Nicholas Ayres
on 18 May 2021
If you are given an equation and told to write a function that would solve the equation when a number is input.
ex.
y=(2/x)*t
x ranges from 0-30
and the input is a value for t.
The main problem is that when i try to use "function" MATLAB says that "function definitions are not permitted in this context"
0 Comments
Accepted Answer
Image Analyst
on 1 Mar 2014
Nicole, you can't have a function follow a script in the same file
test.m:
clc % The script
% Declaring a function like below produces error
% Function definitions are not permitted in this context.
function sub1()
a=10
But you can have two functions in the same m-file:
function test() % first function same name as file.
clc % The script
% Declaring a function like below produces no error
% because file started with a function, not a script.
function sub1()
a=10
3 Comments
Rik
on 18 May 2021
@Nicholas Ayres True, but the specific example will still trigger an error, as functions in scripts need to be closed explicitly with end.
This change is also why the syntax checker became more aggressive for running sections: Matlab needed to be able to detect local functions, so a sytax error in one section could now cause issues. Prior to this, you were allowed some syntax errors in script sections.
Nicholas Ayres
on 18 May 2021
@Rik Very true. I've updated my comment and more directly told people to read the linked documentation.
I like to respond to outdated responses like this as some people may see the old response and not recognise that Matlab is under such active development that an old response can be misleading. :)
More Answers (1)
per isakson
on 1 Mar 2014
- See: Function Basics and
- give it an honest try
- if you run into problems then return here with specific questions
2 Comments
per isakson
on 1 Mar 2014
A function shall be defined (/typed) in a text file. The word function on the first line (may optionally be preceded by comments) and the word end (optionally) on the last line. See Create Functions in Files
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!