How to create a custom function?

15 次查看(过去 30 天)
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"

采纳的回答

Image Analyst
Image Analyst 2014-3-1
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 个评论
Rik
Rik 2021-5-18
@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 2021-5-18
@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. :)

请先登录,再进行评论。

更多回答(1 个)

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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by