필터 지우기
필터 지우기

How to check this condition? (matlab programming)

조회 수: 1 (최근 30일)
RS
RS 2014년 8월 30일
댓글: Image Analyst 2014년 8월 31일
Hi,
I have an randomly generated 100 variables between 1 to 20
a=randi(20,1,100)
and another variable b by
b=randi(20,1,100)
Now I want to select 20 values from a and b such that a*b < 64..
how to select 20 such values from a and b so that the above condition is maintained?
  댓글 수: 1
dpb
dpb 2014년 8월 30일
With/without replacement? But, basically looks like an acceptance/rejection scheme w/ resampling would be the choice. Or, select from one then restrict selection from the other such condition is met; it is trivial in this case to compute the allowable range for the second given the first.

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2014년 8월 30일
At least as I understand the problem, this works:
a=randi(20,1,100); % Initialise random integer arrays
b=randi(20,1,100);
k1 = 1; % Initialise counter and ‘v’
v = [];
while (k1 <= 20) % Limit: 20 pairs of numbers
c1 = a(randi(100)); % Random number from ‘a’
c2 = b(randi(100)); % Random number frin ‘b’
cv = [c1 c2]; % Vector of [a b]
if prod(cv) < 64 % Check: a*b < 64
v = [v; cv]; % If so, add [a b] to ‘v’
k1 = k1 + 1; % Increment counter and continue
end
end

추가 답변 (2개)

Roger Stafford
Roger Stafford 2014년 8월 30일
The following code assumes there are at least 20 such pairs. If not, you will have to regenerate a and b and start over again.
[p,q] = find((a.'*b)<64);
r = randperm(size(p,1),20);
aa = a(p(r));
bb = b(q(r));
The two 20-element column vectors, aa and bb, will be such randomly selected pairs.

Image Analyst
Image Analyst 2014년 8월 30일
편집: Image Analyst 2014년 8월 31일
Try this:
a=randi(20,1,100);
b=randi(20,1,100);
count = 0;
% Compute every product.
for ia = 1 : length(a)
for ib = 1 : length(b)
% Look for a product less than 64.
if a(ia) * b(ib) < 64
% Found one pair that works.
count = count + 1;
% Store it in "keepers" array.
keepers(count, 1) = a(ia);
keepers(count, 2) = b(ib);
end
end
end
% Print to command window:
keepers
% Keep only the first 20 of them or however many of them there are.
lastIndex = min(20, length(keepers));
keepers = keepers(1:lastIndex);
  댓글 수: 2
RS
RS 2014년 8월 31일
Thank you all,
All 3 logic are very useful.
Image Analyst
Image Analyst 2014년 8월 31일
Note though that they are different. My code exhaustively checks every number in a multiplied by every number in b. So every pair is checked, and checked only once. Star's code takes random selections from a and b and checks them, so it might check (and select/keep) some products twice while others not at all .

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Hypothesis Tests에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by