How can i write a function similiar to randi for MATLAB v 2007b?

14 views (last 30 days)
Hello,
Unfortunately, for our research project we have to use a desktop with the old MATLAB 2007b version and for unknown reasons we are not allowed to upgrade it. However, I need to downgrade a script to run on MATLAB 2007b version and Psychotoolbox 3.0.11.
In the script, we use Randi a lot. Since this function was introduced in 2008, it doesn't work anymore. Now I am trying to write my own function, but it is not really successful so far.
I don't get any direct errors from my randi script. The task starts to run, but then it crashes because some functions are undefined and I suspect it is because my randi function is not working properly and therefore the following variables are not defined properly.
This is the script I used:
Translated with www.DeepL.com/Translator (free version)
%Function that does similiar as randi
function i = randi_old(n, dims)
if nargin < 1 || nargin > 2
error('Usage: i = randi_old(n, [dims])');
end
if nargin < 2 || isempty(dims)
dims = [1, 1];
end
if numel(dims) == 1
dims = [1, dims];
end
% Set the random seed based on the current time
seedValue = sum(100*clock);
rand('seed', seedValue);
i = floor((n+1) * rand(dims));
end
Thanks for any tips regarding that issue!

Accepted Answer

Lukas
Lukas on 8 Jun 2023
Hey guys,
thanks for your answers so far!
It looks like the code & task is running now. At least i was able to run the whole task before leaving the lab in the afternoon, still have to check the datafile etc.
This is the final code with which the task ran. Just in case anyone might need that in the future (Hopefully noone has to do this haha)
function i = randi_old(n, dims)
if nargin < 1 || nargin > 2
error('Usage: i = randi_old(n, [dims])');
end
if nargin < 2 || isempty(dims)
dims = [1, 1];
end
if numel(dims) == 1
dims = [1, dims];
end
% Set the random seed based on the current time
seedValue = sum(100*clock);
rand('seed', seedValue);
i = floor((n+1) * rand(dims));
% Adjust generated random values to match the desired range [1, n]
i = mod(i-1, n) + 1;
end
Apparently the range adjustment was important. Beforehand i got errors regarding the generated numbers.
But again, thanks for the quick suggestions!

More Answers (1)

the cyclist
the cyclist on 8 Jun 2023
Edited: the cyclist on 8 Jun 2023
I'm not absolutely certain it will have all the properties of randi, but I think you should be able to use ceil(imax*rand()) in the same way you would have used randi(imax). (It may even be literally that under the hood.)
imax = 6;
N = 7;
rng default
randi(imax,N,1)
ans = 7×1
5 6 1 6 4 1 2
rng default
ceil(imax*rand(N,1))
ans = 7×1
5 6 1 6 4 1 2

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2007b

Community Treasure Hunt

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

Start Hunting!