Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 1 (최근 30일)
The Legend
The Legend 2019년 12월 16일
마감: MATLAB Answer Bot 2021년 8월 20일
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
Mohammad Sami
Mohammad Sami 2019년 12월 17일
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 2019년 12월 17일
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.

답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by