Erstellen einer Funktion in MATLAB (2024)

Erstellen einer Funktion in MATLAB (1)

In diesem Tutorial wird die Erstellung von Funktionen mit der Variablen function in MATLAB erläutert.

Erstellen Sie eine Funktion mit der Variablen function in MATLAB

Eine Funktion in Matlab besteht hauptsächlich aus drei Dingen: Ausgabe, Eingabe und Funktionsname. Um eine Funktion zu definieren, verwenden wir die Variable function und definieren dann die Ausgänge, den Funktionsnamen und die Eingänge der Funktion. Danach schreiben wir unseren Code in die Funktion. Der Funktionsname sollte mit einem alphabetischen Zeichen beginnen, und ein Funktionsname kann Zahlen, Ziffern und Unterstriche enthalten. Um das Ende einer Funktion anzuzeigen, können wir die Variable end verwenden. Sehen Sie sich zum Beispiel den folgenden Code an.

function outputs = function_Name(inputs) Your codeend

Eine Funktion kann nur einen Ausgang haben. Lassen Sie uns zum Beispiel eine Funktion definieren, die ein Array von Zahlen akzeptiert, und die Ausgabe der Funktion ist der Durchschnitt des Arrays. Siehe den Code unten.

vect = [1 3 5]averg = average(vect)function a = average(v)a = mean(v);end

Ausgabe:

vect = 1 3 5averg = 3

Eine Funktion kann auch zwei Ausgänge haben. Lassen Sie uns zum Beispiel eine Funktion definieren, die ein Array akzeptiert und uns den Mittelwert des Arrays und die Standardabweichung liefert. Siehe den Code unten.

vect = [1 3 5][averg, stanD] = average(vect)function [a,s] = average(v)a = mean(v);s = std(v);end

Ausgabe:

vect = 1 3 5averg = 3stanD = 2

Wir können eine Funktion in einer Skriptdatei definieren, müssen sie jedoch am Ende des Codes definieren. Sie können auch mehrere Funktionen in einer einzigen Datei definieren, und alle Funktionen sollten sich am Ende des Codes befinden. Eine Funktion kann auch eine andere Funktion aufrufen. Sie können beispielsweise zwei Funktionen definieren und die zweite Funktion kann die erste Funktion aufrufen. Wir können auch Funktionen mit Eingabevalidierung definieren, um die Eingaben zu überprüfen. Lassen Sie uns zum Beispiel eine Funktion definieren, die die Eingabe überprüft, ob es eine Ganzzahl ist oder nicht, und wenn es eine Ganzzahl ist, führt sie die Operation aus; Andernfalls wird ein Fehler gesendet. Das können wir mit den variablen Argumenten tun. Siehe den Code unten.

vect = 'a';[averg, stanD] = average(vect)function [a,s] = average(v)arguments v {mustBeNumeric, mustBeFinite} enda = mean(v);s = std(v);end

Ausgabe:

Error using Untitled>averageInvalid argument at position 1. Value must be numeric.Error in Untitled (line 3)[averg, stanD] = average(vect)

Im obigen Code haben wir anstelle eines numerischen Arrays einen String übergeben, und Matlab hat einen Fehler angezeigt, der besagt, dass der Wert numerisch sein muss. Denken Sie daran, dass Sie beim Aufrufen einer Funktion die spezifischen Ein- und Ausgänge bereitstellen sollten. Wenn wir beispielsweise eine Funktion mit zwei Eingängen und zwei Ausgängen definiert haben, sollten wir während des Funktionsaufrufs zwei Eingänge und zwei Ausgänge definieren; Andernfalls wird ein Fehler angezeigt, wenn Sie jedoch eine Funktion mit einer variablen Anzahl von Ausgängen und Eingängen definieren möchten. Wir können dies tun, indem wir die Variable varargin verwenden, um die Variableneingaben einer Funktion zu definieren. Wir können die Variable nargin verwenden, die uns sagt, wie viele Eingaben der Benutzer gemacht hat. Danach können wir Bedingungen für die Eingaben festlegen. Zum Beispiel können wir Anforderungen definieren, dass, wenn der Benutzer eine Eingabe eingibt, dies die Ausgabe ist, und wenn der Benutzer zwei Eingaben eingibt, dies die Ausgabe ist und so weiter. Lassen Sie uns zum Beispiel eine Funktion definieren, die uns die Anzahl der vom Benutzer eingegebenen Eingaben liefert. Siehe den Code unten.

NumInputs('a',2,"start")function NumInputs(varargin) disp("Number of inputs: " + nargin) celldisp(varargin)end

Ausgabe:

Number of inputs: 3 varargin{1} = a  varargin{2} =  2  varargin{3} = start

Außerdem können wir mit der Variable varargout variable Ausgaben in einer Funktion definieren und mit der Variablen nargout verfolgen, wie viele Ausgaben der Benutzer definiert hat. Lassen Sie uns zum Beispiel eine Funktion definieren, die uns den Mittelwert und die Standardabweichung liefert. Wenn der Benutzer nur einen Ausgang definiert, gibt die Funktion nur den Mittelwert des Arrays zurück. Wenn der Benutzer zwei Ausgabevariablen definiert, gibt die Funktion die Standardabweichung und den Mittelwert des Arrays zurück. Siehe den Code unten.

v = [1 2 6];[m]= AVGSTD(v)[mean,st] = AVGSTD(v)function [m,varargout] = AVGSTD(v) m = mean(v); if(nargout>1) varargout{1} = std(v); endend

Ausgabe:

m = 3mean = 3st = 2.6458

Im obigen Code haben wir die Funktion AVGSTD() zweimal aufgerufen, das erste Mal mit nur einem Ausgang und das zweite Mal mit zwei Ausgängen. Beim ersten Aufruf gab die Funktion nur den Mittelwert zurück, beim zweiten Aufruf gab die Funktion den Mittelwert und die Standardabweichung zurück. Wir können auch die Anzahl der Ausgaben mit dem Variablenargument validieren. Wenn der Benutzer beispielsweise versucht, mehr als zwei Variablen in die Ausgabe einzugeben, können wir ihm einen Fehler anzeigen, dass diese Funktion nur zwei Ausgaben akzeptiert. Wir können auch wiederverwendbare Funktionen in Matlab definieren, die in einer Datei gespeichert werden, und wir können sie mit dem Dateinamen aufrufen. Um eine solche Funktion zu definieren, müssen wir nur die Matlab-Datei im Namen der Funktion benennen. Wenn die Funktion beispielsweise den Namen Durchschnitt hat, sollte die Matlab-Datei denselben Namen haben. Um die Funktion aufzurufen, müssen wir eine weitere Skriptdatei im selben Verzeichnis erstellen, in dem die Funktionsdatei abgelegt wurde, und wir können die Funktion mit ihrem Namen in der Skriptdatei aufrufen.

Erstellen einer Funktion in MATLAB (2024)

FAQs

How do you define a function in MATLAB? ›

function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts inputs x1,...,xM and returns outputs y1,...,yN . This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

How to convert symbolic to function in MATLAB? ›

ht = matlabFunction( f ) converts the symbolic expression or function f to a MATLAB® function with handle ht . If there is an equivalent MATLAB function operating on the double data type for the symbolic expression or function, then the converted function can be used without Symbolic Math Toolbox™.

How to define a function? ›

A function is defined as a relation between a set of inputs having one output each. In simple words, a function is a relationship between inputs where each input is related to exactly one output. Every function has a domain and codomain or range. A function is generally denoted by f(x) where x is the input.

How do I add a function to MATLAB? ›

To create a script or live script with local functions, go to the Home tab and select New Script or New Live Script. Then, add code to the file. Each local function must begin with its own function definition statement and end with the end keyword.

How to run a function in MATLAB? ›

MATLAB runs the function using the first run command in the list. For example, click Run to run myfunction using the command result = myfunction(1:10,5) . MATLAB displays the result in the Command Window. To run the function using a different run command from the list, click Run and select the desired command.

How to define a function as a symbolic function in MATLAB? ›

f( inputs ) = formula creates the symbolic function f . For example, f(x,y) = x + y . The symbolic variables in inputs are the input arguments. The symbolic expression formula is the body of the function f .

How to use inbuilt function in MATLAB? ›

Use builtin to execute the original built-in from within a method that overloads the function. To work properly, you must never overload builtin . [y1,...,yn] = builtin( function , x1,...,xn ) stores any output from function in y1 through yn .

What are function variables in MATLAB? ›

MATLAB Function blocks use variables to manage simulation data. Variables can represent data for block inputs, outputs, parameters, or from Data Store Memory blocks. You can create or delete variables in the MATLAB Function block code, the Symbols pane, or the Model Explorer.

How to implement step function in MATLAB? ›

[ y , tOut ] = step( sys , tFinal ) computes the step response from t = 0 to the end time t = tFinal . [ y , tOut ] = step( sys , t ) returns the step response of a dynamic system model sys at the times specified in the vector t .

What is generate function in MATLAB? ›

You can use matlabFunction to generate a MATLAB® function handle that calculates numerical values as if you were substituting numbers for variables in a symbolic expression. Also, matlabFunction can create a file that accepts numeric arguments and evaluates the symbolic expression applied to the arguments.

What is an example of a symbolic function? ›

For example, a child playing with a toy can mentally picture and experience the toy even after it has been taken away and they can no longer see it. Symbolic function emerges early in the preoperational stage and is expressed through deferred imitation, language, symbolic play, and mental imagery.

How do you define a step function in MATLAB? ›

[ y , tOut ] = step( sys , t ) returns the step response of a dynamic system model sys at the times specified in the vector t .

How to define an inline function in MATLAB? ›

f = inline( expr , arg1,arg2,…,argN ) constructs an inline function whose input arguments are specified by arg1,arg2,…,argN . Multicharacter symbol names may be used. f = inline( expr , N ) , where N is a scalar, constructs an inline function whose input arguments are x and P1,P2,…,PN .

How do you define an expression in MATLAB? ›

An expression used in a class definition can be any valid MATLAB® statement that evaluates to a single array. Use expressions to define property default values and in attribute specifications. Expressions are useful to derive values in terms of other values.

Top Articles
The 2024 World Series of Poker (WSOP) Schedule is Out; 99 Live Bracelet Events
WSOP 2024 Full Schedule is Here -- 99 Bracelets, A Dozen New Events
Navicent Human Resources Phone Number
Whas Golf Card
Aberration Surface Entrances
The Ivy Los Angeles Dress Code
How to Type German letters ä, ö, ü and the ß on your Keyboard
Palace Pizza Joplin
Jasmine
Rls Elizabeth Nj
FIX: Spacebar, Enter, or Backspace Not Working
The Weather Channel Facebook
Regal Stone Pokemon Gaia
Gas Station Drive Thru Car Wash Near Me
Miss America Voy Forum
Luna Lola: The Moon Wolf book by Park Kara
Ts Lillydoll
Magic Mike's Last Dance Showtimes Near Marcus Cedar Creek Cinema
Operation Cleanup Schedule Fresno Ca
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
Www Craigslist Milwaukee Wi
Jalapeno Grill Ponca City Menu
Candy Land Santa Ana
Lehmann's Power Equipment
Wausau Marketplace
Delaware Skip The Games
Outlet For The Thames Crossword
Att.com/Myatt.
Busted Mcpherson Newspaper
Www.paystubportal.com/7-11 Login
Watch Your Lie in April English Sub/Dub online Free on HiAnime.to
Play Tetris Mind Bender
The 15 Best Sites to Watch Movies for Free (Legally!)
Divina Rapsing
Ullu Coupon Code
Babydepot Registry
Brenda Song Wikifeet
Colin Donnell Lpsg
Jambus - Definition, Beispiele, Merkmale, Wirkung
Yoshidakins
Facebook Marketplace Marrero La
The 50 Best Albums of 2023
Husker Football
Live Delta Flight Status - FlightAware
התחבר/י או הירשם/הירשמי כדי לראות.
Exploring the Digital Marketplace: A Guide to Craigslist Miami
Swsnj Warehousing Inc
Bf273-11K-Cl
Verizon Forum Gac Family
Congressional hopeful Aisha Mills sees district as an economical model
Tamilyogi Cc
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 5475

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.