generate two variable from distribution without same result
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi there, if we have two variables are generated from uniform distribution as : A=randi([0,5],1,6); B=randi([-4,4],1,6);
Now I want some simple steps that can make: A and B are both vector, and I define that C(i)=[A(i) B(i)], i=1:6; then I dont want any of rows of C are the same. How should I do for the randi to make this happen?
2 Kommentare
Dyuman Joshi
am 11 Jan. 2023
"I dont want any of rows of C are the same."
It is unclear to me what exactly it means. Please give an example.
Meanwhile, I have attempted something based on an assumption, let me know if it works or not.
A=randi([0,5],1,6)
B=randi([-4,4],1,6)
while any(A==B)
B=randi([-4,4],1,6);
end
C=[A' B']
Antworten (2)
Walter Roberson
am 11 Jan. 2023
one of the ways is to prevent it from happening at all, by excluding the random A from the values available to be chosen from.
Achoices = 0:5;
numA = length(Achoices);
Bchoices = -4:4;
for row = 1 : 6
A = Achoices(randi(numA));
availableB = setdiff(Bchoices, A);
B = availableB(randi(numel(availableB)));
C(row,:) = [A, B];
end
Another way is to generate 6 entries freely without any conflict control, and then to remove rows that have duplicates, and then go back and generate as many more entries as you need. You would want a loop for this, each time generating (6 minus the number already generated), as it is possible for the new attempts to also happen to have conflicts.
Oh way... are you asking that the A and B entries of any one row are not the same, or is that acceptable but no two rows of C can be the same as other rows? If so then the loop generating some and removing duplicates and going back to generate any missing ones works fine.
Sometimes people improve the random efficiency by generating more entries than they need, expecting that some will probably clash, and hoping that enough non-clash will be left over after removing duplicates. You generally still need some looping if you do that, just not as many loop trips on average.
Bruno Luong
am 11 Jan. 2023
Bearbeitet: Bruno Luong
am 11 Jan. 2023
Warranty never repeated pairs
lA = 0; uA = 5; % lower upper bound of A
lB = -4; uB = 4; % and B
n = 50; % number of pair elements to be generated, 6 in your case
mA = (uA-lA)+1;
mB = (uB-lB)+1;
[iA,iB] = ind2sub([mA,mB], randperm(mA*mB,n));
A = lA-1+iA,
B = lB-1+iB,
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!