2

I am writing a Matlab script which requires the repeated generation of random numbers. I am running into an issue where if I pass my random generation function as a parameter to another function, then within the function to which it is passed, it only evaluates once.

Here is some example code:

This is my file randgen.m:

function number = randgen()
    'HELLO WORLD'
    number = rand(1);
end

Here is my file problemtester.m:

function arr = problemtester(rgen)
firstrand = rgen();
for i = 1:1000
    arr(i) = rgen();
end

When I run the command

x = problemtester(randgen);

HELLO WORLD is printed once, and x is filled with 1000 copies of the same random number, so the function must only have evaluated once even though the loop ran 1000 times. Why is this function only evaluating once, despite the repeated calls to it, and more importantly, how do I make it call on each loop iteration?

2
  • 1
    I think you are mixing variable and function names. Commented Jul 13, 2016 at 15:08
  • that would make sense, but why does it behave like a function the first time, but a variable on all future iterations? Commented Jul 13, 2016 at 15:09

1 Answer 1

4

By calling the function with

x = problemtester(randgen)

MATLAB will first evaluate randgen, as this is a function (and is callable without any parameters). At that time, HELLO WORLD is printed. The return value of that function call is then passed to problemtester, which saves this one value 1000 times into arr and returns that.

To make problemtester call the function randgen, you have to supply a function handle, which is MATLAB's equivalent to function pointers.

x = problemtester(@randgen)

This prints HELLO WORLD a thousand times, and returns a nice random vector.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.