Generate random numbers in a loop and then store them
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
KALYAN ACHARJYA
2019-8-27
编辑:KALYAN ACHARJYA
2019-8-27
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?.
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!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!