anonymous function with rng call inside

I would like to have a time domain function that uses a random number, but is stable over an interval. The anonymous function below does this, but it is not elegant.
f = @(t) {rng(ceil(t/10)), rand(1)}; % returns new random numbers each decade of t
f(2)
ans =
1×2 cell array
{1×1 struct} {[0.4170]}
The random number in second cell is what I want, but it can only be accessed through another variable. Is there a way in Matlab to simply return the random number without all the indirection?
Thank you for any help you can offer.

4 Comments

Sometimes you just need to ask the question and then it comes to you!
f = @(t) isstruct(rng(ceil(t/10)))*rand(1);
Are there bounds on t?
f = @(t) isstruct(rng(ceil(t/10)))*rand(1);
Not a good idea. You are assuming sub-expressions in the function are evaluated left-to-right. That is not reliable.Why does the function have to be anonymous?
MATLAB has a well-defined order of operations, that mostly guarantees left-to-right operations (as modified by the operation precedences, that leads to oddities like c^a^b ). The main exception is the vaguely-documented linear algebra exceptions where for example a'*b might be specially evaluated rather than being evaluated as (a')*b

Sign in to comment.

 Accepted Answer

f = @(t) struct('rng', rng(ceil(t/10)), 'r1', rand(1)).r1
f = function_handle with value:
@(t)struct('rng',rng(ceil(t/10)),'r1',rand(1)).r1
f(2)
ans = 0.4170

More Answers (3)

Matt J
Matt J 3 minutes ago
Edited: Matt J 2 minutes ago
function y=f(t)
rng(ceil(t/10));
y=rand(1);
end
t = 2*(rand(1,1000)-0.5)*100;
figure
plot(t,f(t,10),'b.',t,f(t,10),'r.')
function y = f(t,interval)
tinterval = ceil(t/interval);
[C,ia,ic] = unique(tinterval);
yout = rand(size(C));
y = yout(ic);
end
rng('default')
T= rand(1,10);
t=1:15;
T(ceil(t/10))
ans =
Columns 1 through 9
0.8147 0.8147 0.8147 0.8147 0.8147 0.8147 0.8147 0.8147 0.8147
Columns 10 through 15
0.8147 0.9058 0.9058 0.9058 0.9058 0.9058

Products

Release

R2025a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!