What is the purpose of defining a function like this?

6 visualizzazioni (ultimi 30 giorni)
Hello, I'm quite new to matlab and am learning it as part of my degree. I was just curious as to why a function my be declared like this:
function [zero,inc,res,niter] = newtonsys(Ffun,Jfun,x0,tol,nmax)
I'm curious because the variables like Ffun and X0 are variables that i end up declaring in the body of the function anyway? Am i missing a more convienet way of declaring them without typing in the body:
Ffun = ....
Thank you in advance for any clarity you can provide

Risposte (1)

Steven Lord
Steven Lord il 7 Mag 2020
I'm curious because the variables like Ffun and X0 are variables that i end up declaring in the body of the function anyway?
Don't overwrite the inputs to your function. Doing so wastes (probably only a small amount) of effort by declaring variables you're not going to use, but it also destroys the generality of your newtonsys function.
Based on the names I suspect the author of this code intended callers to pass function handles into the function for the Ffun and jfun inputs. If so this is similar to other functions like the ODE solvers (ode45 is the most commonly used example) and the integration functions like integral.
Let's use the idea of integration as an example. If I want to compute the integral of two functions, and , I could write a function to compute the integral of , use it to compute the integral, then modify its source code to compute the integral of and use the modified code to compute its integral. But I want to be lazy, write the source code once and use it on both functions without having to modify the integration function. Function handles let you do that.
f = @(x) x.^2; % anonymous function handle
g = @sin; % "regular" function handle
intF = integral(f, 0, 1)
intG = integral(g, 0, pi/2) % I made no modification to integral between these calls
As an analogy, a function handle is the "phone number" of the function in question. You don't have a separate physical phone for each and every person whose phone number you possess, right? In this analogy, the integral function is the phone and the function handles are the phone numbers that tell the phone to whom you wish to speak.
The newtonsys function you posted is a phone, just like integral. The analogy breaks down a little bit at this point, but maybe instead of being physical devices integral is the phone app and newtonsys is the text messaging app. They do different things, but they both can use phone numbers.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Prodotti


Release

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by