Creating arrays of unknown length
Show older comments
I am trying to write a function that generates a sequence of random integer numbers between 1 and m, stopping when a value is repeated for the first time. The function would generate an array containing all the numbers generated except for the last value that is a repeated occurrence. For example, if the generated sequence is 3 1 9 5 7 2 5, the array to be returned should be 3 1 9 5 7 2. Below is the code that I have so far; I feel that I am close, but that I'm missing smth trivial. Any insight would be extremely appreciated.
function [v] = sequence_CM(m)
for i=1:m
A(i)=ceil(2+((100+100)*rand(1)));
B(i)=A(i);
for k=((i+1):length(B))
if B(i)==A(i+1)
break;
end
end
end
v=A;
Accepted Answer
More Answers (2)
Image Analyst
on 31 Dec 2015
You can use unique and check the length of it. If there are repeats, the length of hte unique array will be less than the original array. Not sure how fast it is, but it works.
m = 10 % whatever you want.
randomIntegers = randi(m, 1, m)
for k = 2 : length(randomIntegers)
% Get the array from index 1 up to index k.
thisArray = randomIntegers(1:k)
% Check if the number of unique numbers matches the length of the array.
% If it does, all are unique and there are no repeats.
% If it does not, then there must now be a repeat.
if length(unique(thisArray)) < k
% There must be a duplicate.
break
end
end
% Extract numbers just up to index (k-1) - we don't want the repeated integer.
randomIntegers = randomIntegers(1:k-1)
1 Comment
Asif Khan
on 22 Nov 2020
this is wrong
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!