How to create a custom function?

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"

 Accepted Answer

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

Nicholas Ayres
Nicholas Ayres on 18 May 2021
Edited: Nicholas Ayres on 18 May 2021
For anybody who stumbles across this, the above answer is now outdated, as local functions within scripts was added in R2016b.
However, if you do this, you MUST "end" the function.
I recommend reading the documentation linked below before trying!
@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.
@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. :)

Sign in to comment.

More Answers (1)

per isakson
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

The main problem is that when i try to use "function" MATLAB says that "function definitions are not permitted in this context". I can type in an exact problem from a book,and save the file, but i will get an error.
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

Sign in to comment.

Categories

Find more on Programming 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!