How to create a custom function?

15 Ansichten (letzte 30 Tage)
Nicole Isbell
Nicole Isbell am 1 Mär. 2014
Kommentiert: Nicholas Ayres am 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"

Akzeptierte Antwort

Image Analyst
Image Analyst am 1 Mär. 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 Kommentare
Rik
Rik am 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 am 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. :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by