Take the 2-minute tour ×
Computational Science Stack Exchange is a question and answer site for scientists using computers to solve scientific problems. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 5 down vote accepted
  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.

share|improve this answer
    
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? –  AlanH Dec 30 '12 at 1:06
2  
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

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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