Reputation: 156
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?
Upvotes: 2
Views: 29
Reputation: 14316
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.
Upvotes: 4