3
$\begingroup$

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.

$\endgroup$

2 Answers 2

5
$\begingroup$
  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.

$\endgroup$
2
  • $\begingroup$ 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? $\endgroup$ Commented Dec 30, 2012 at 1:06
  • 2
    $\begingroup$ 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. $\endgroup$
    – Bill Barth
    Commented Dec 30, 2012 at 4:02
1
$\begingroup$

I think I get your point, which this answer hasn't got.

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.