MATLAB Answers

Generate random numbers in a loop and then store them

9 views (last 30 days)
JL
JL on 27 Aug 2019
Commented: JL on 27 Aug 2019
I have the code below where I want to generate 1 000 000 random numbers. Then I compare random numbers generated from A to B. If A is B, number is 1 else its 0. What I did next is to remove non-zero rows, and keep rows that has zeros.
A = rand(1000000, 5); % generate 1 000 000 samples
B = [0.0012 0.0018 0.0012 0.0012 0.0012]; % values of B
res = bsxfun(@gt,A,B); % to compare A>B, if A is greated than B, 1 else 0
mask=~all(res,2); % to remove non-zeros rows
subset = res(mask,:); % list down all the rows that has zeros
d = bi2de(subset); % to convert binary to decimal
First question, is there a code that store non-zeros rows? Second question, I'm using this code to below to remove non-zeros rows that are the same (by using converting binary to decimal.
out0 = d(all(diff(sort(d,2),1,2) > 1e4*eps,2),:);
out1 = sortrows(out0);
loc = [true;all(diff(out1,1,1),2)];
out = out1(loc,:);
2nd question, using the code above, is there a way count the same number?.
3rd question, how can i used a for loop using the code above? I want to run the 1 000 000 samples 10 times, and each time, I want to store new non-zeros rows that appears for each run and count each time it appears each run.
I want to have
T = [1 1 1 0 0 7
1 0 1 1 0 13
0 1 1 1 0 14
1 1 1 1 0 15
1 1 0 0 1 19
1 0 1 0 1 21
1 1 1 0 1 23
1 0 0 1 1 25
0 1 0 1 1 26
1 1 0 1 1 27
0 0 1 1 1 28
1 0 1 1 1 29
0 1 1 1 1 30]
  2 Comments
JL
JL on 27 Aug 2019
Hi Adam, but my idea is to create more random samples subsequently. Like looping it 100 times? or more?

Sign in to comment.

Answers (1)

KALYAN ACHARJYA
KALYAN ACHARJYA on 27 Aug 2019
Edited: KALYAN ACHARJYA on 27 Aug 2019
First question, is there a code that store non-zeros rows?
See this example:
A=randi(10,2,4);
A(3,:)=0;
% Store Non Zero rows only
idx=any(A==0,2) % Find the zeros rows
A(idx,:)=[]; % Remove the Zero rows
A
Second question, I'm using this code to below to remove non-zeros rows that are the same (by using converting binary to decimal.
Simple trick: (Apply this after removing zero rows)
result=unique(A,'rows')
Another
2nd question, using the code above, is there a way count the same number?.
See here, same question
3rd question, how can i used a for loop using the code above? I want to run the 1 000 000 samples 10 times, and each time, I want to store new non-zeros rows that appears for each run and count each time it appears each run.
May be:
var_name={};
for i=1:samples_num
for j=1:10
var_name{i,j}=save new non-zeros rows
%count each time it appears each run...I did not undestand this line
end
end
Hope it helps!

Community Treasure Hunt

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

Start Hunting!

Translated by