How to check this condition? (matlab programming)
2 ビュー (過去 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
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
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
0 件のコメント
その他の回答 (2 件)
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.
0 件のコメント
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 件のコメント
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 Center および File Exchange で Financial Toolbox についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!