How to check this condition? (matlab programming)

1 次查看(过去 30 天)
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 .

请先登录,再进行评论。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by