Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

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

2 Ansichten (letzte 30 Tage)
The Legend
The Legend am 16 Dez. 2019
Geschlossen: MATLAB Answer Bot am 20 Aug. 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 Kommentare
Mohammad Sami
Mohammad Sami am 17 Dez. 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 am 17 Dez. 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.

Antworten (0)

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by