Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Why isn't the code properly distributing the 1's and 2's in the ratio 3:4 or 4:3?

1 vue (au cours des 30 derniers jours)
The Legend
The Legend le 16 Déc 2019
Clôturé : MATLAB Answer Bot le 20 Août 2021
Why isn't the code distributing the 1's and 2's in the ratio 3:4 or 4:3?
Why is it outputting zeros where it shouldn't (look at highlighted output below)?
clear;
close all;
clc;
N = 4;
K = 14;
M = zeros(N + 2,N + 3);
colNum = 1;
rowNum = N + 2;
i = K * 2;
yellow = 0;
red = 0;
half = (N + 3) / 2 + 1;
counter = 0;
while i ~ 0;
random = randi(2,1,1);
if random == 1
constant = yellow;
elseif random == 2
constant = red;
end
if constant < 4
if random == 1
num = 1;
yellow = yellow + 1;
elseif random == 2
num = 2;
red = red + 1;
end
M(rowNum,colNum) = num;
elseif constant > 4
if random == 1
num == 2;
red = red + 1;
elseif random == 2
num == 1;
yellow = yellow + 1;
end
M(rowNum,colNum) = num;
end
counter = counter + 1;
counterDev = rem(counter,N + 3);
if counterDev == 0
rowNum = rowNum - 1;
yellow = 1;
red = 1;
end
if counterDev == 0;
colNum = 1;
else
colNum = colNum + 1;
end
i = i - 1;
end
It is outputting zeros (highlighted below) when it should output a one or two on that spot:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
2 2 2 1 1 *0* *0*
2 1 2 2 *0* *0* *0*
2 2 1 1 2 1 *0*
2 2 1 1 1 1 2
  3 commentaires
Mohammad Sami
Mohammad Sami le 17 Déc 2019
It's not clear what you are trying to accomplish.
If you are just trying to randomly assign ones and twos, then perhaps you can do it like this
N = 4
a = rand(N+2,N+3);
i = a<(4/7);
a(i) = 1;
a(~i) = 2;
Walter Roberson
Walter Roberson le 17 Déc 2019
If you want a fixed ratio of random values, then create a vector containing the exact number desired of each value, and use randperm() to create a random ordering to apply to the vector.

Réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by