# Handling function inputs in Matlab

Say I have a function

function u = somefxn(f,n)


where f is some function, say f = pi^2*sin(pi*x), and n is the number of discretizations (let n = 1024) on the interval $[0,1]$. In my code I've written

h = 1/n %n = 1024
x = 0:h:1 %discretizations


But what if the user uses y or z in the function instead of x? How do I handle that uncertainty?

Please let me know if this isn't clear. I'm rather new to Matlab.

1. The function f has (should have?) its own local variable, the name of which is independent of the calling scope.

2. It's much better to use x = linspace(0,1,n+1) than x = 0:1/n:1 because the latter is susceptible to rounding error.

• I'm confused about how functions are handled though. If I were to enter the same function but using f(y) instead of f(x), and my code includes x = linspace(0,1,n+1), then will it recognize that y should be treated as x? – TheRealFakeNews Dec 30 '12 at 1:06
• Jed has explained the situation pretty clearly in his point #1, but perhaps using words and concepts that you do not know. When you define the function f(something), inside the the function, f, the variable is known as something containing the argument you passed to f, but when you call f, you may pass the name of any variable you have already used/defined. So you may call f(x) or f(y) or f(whatever) as long as x, y, or whatever have been defined. Variable names in MATLAB are not shared between functions unless they are explicitly made global using the global keyword. – Bill Barth Dec 30 '12 at 4:02

Do you mean literally something like

x=1:0.1:10;
f=(pi^2)*sin(pi*x);


?

Then f is no longer a function. It is just a variable containing the result of the function applied to the x that you already have. In other words, your function has already been evaluated.

In this case, the answer to your question is that you don't need to do anything : f simply does not know about x, or other variable.

Depends on what's the exact code in question.