MATLAB: Creating arrays of unknown length

arrays of unknown length

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;

Best Answer

Your code is treating m as a maximum length, with the generated values being integers in the range 3 to 202. But your description implies that m should be the maximum allowed random value -- which would also provide a natural maximum length by the pigeon hole principle (you cannot generate more than m different random integers in the range 1 to m without there being a duplicate.)
Your code is adding the new test value to both A and B, and is returning the full A. But when a duplicate is finally generated it is not to be put into the answer, according to your description.
It seems a waste of effort to maintain your B vector.
Hint: ismember(newvalue, A) and if it is not there then append newvalue to A, otherwise stop.