How to create a custom function?

15 vues (au cours des 30 derniers jours)
Nicole Isbell
Nicole Isbell le 1 Mar 2014
Commenté : Nicholas Ayres le 18 Mai 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"

Réponse acceptée

Image Analyst
Image Analyst le 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 commentaires
Rik
Rik le 18 Mai 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
Nicholas Ayres le 18 Mai 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. :)

Connectez-vous pour commenter.

Plus de réponses (1)

per isakson
per isakson le 1 Mar 2014
  • See: Function Basics and
  • give it an honest try
  • if you run into problems then return here with specific questions
  2 commentaires
Nicole Isbell
Nicole Isbell le 1 Mar 2014
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.
per isakson
per isakson le 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by