Replace repeated pair of coordinates generated from 'randi' statement.
Show older comments
N=input('How many pairs?');
randnos=randi(10,N,2);
The above statement generates N pairs of coordinates as a Nx2 array. When N goes big, such as 25, randnos contains repeated coordinate pairs as generated by randi function. Any method or a piece of code to replace the repeated pair with some other different pair?
Answers (3)
KSSV
on 20 Jun 2018
N=input('How many pairs?');
% randnos=randi(10,5,2)
idx = randperm(100,N*2) ;
randnos = reshape(idx,N,2)
1 Comment
Vatsal Gupta
on 21 Jun 2018
Steven Lord
on 20 Jun 2018
Use randperm to generate random unique linear indices.
If you need subscripts rather than linear indices, convert the linear indices into subscripts using ind2sub. If you're planning to use those indices to assign values into specific elements of a matrix, you probably want to stick with the linear indices (or at least keep them around for the purpose of assignment, even if you need the subscripts for display or other purposes.)
linInd = randperm(100, 7);
[rowInd, colInd] = ind2sub([10 10], linInd);
ALin = zeros(10);
ALin(linInd) = 1
ASub = zeros(10);
ASub(rowInd, colInd) = 1
This replies N different pairs of numbers between 1 and Len:
N = 35;
Len = 10; % Numbers from 1 to 10
K = (1:Len).';
Pool = [repmat(K, Len, 1), repelem(K, Len, 1)];
Index = randperm(size(Pool, 1), N);
Result = Pool(Index, :);
As long as Len is not too large, creating all possible pairs at first is not too expensive. But for e.g. Len = 1e5 another strategy more efficient:
N = 35;
Len = 1e5;
Result = [];
Limit = 1e6;
iLimit = 0;
while size(Result, 1) < N
new = randi(Len, N - size(Result, 1), 2);
Result = union(Result, new, 'rows');
iLimit = iLimit + 1;
if iLimit > Limit
error('Cannot find list of pairs by rejection method.')
end
end
index = randperm(N, N); % union sorts the output, mix it again
Result = Result(index, :);
This can fail, if you request more than the possible number of pairs, or it can be slow, if N is large and near to the possible limit.
1 Comment
Vatsal Gupta
on 26 Jun 2018
Categories
Find more on Matrix Indexing 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!