Borrar filtros
Borrar filtros

How to check this condition? (matlab programming)

1 visualización (últimos 30 días)
RS
RS el 30 de Ag. de 2014
Comentada: Image Analyst el 31 de Ag. de 2014
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 comentario
dpb
dpb el 30 de Ag. de 2014
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.

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 30 de Ag. de 2014
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

Más respuestas (2)

Roger Stafford
Roger Stafford el 30 de Ag. de 2014
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 el 30 de Ag. de 2014
Editada: Image Analyst el 31 de Ag. de 2014
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 comentarios
RS
RS el 31 de Ag. de 2014
Thank you all,
All 3 logic are very useful.
Image Analyst
Image Analyst el 31 de Ag. de 2014
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 .

Iniciar sesión para comentar.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by