필터 지우기
필터 지우기

How to randomize the color of two objects so that are not the same color?

조회 수: 1 (최근 30일)
Here is my code:
random = rand(1)
if random <(1/4)
colour1 = [200 200 0]
elseif random>=(1/4) && random<(2/4)
colour1 = [200 0 0]
elseif random>=(2/4) && random<(3/4)
colour1 = [0 200 0]
elseif random>=(3/4) && random<(4/4)
colour1 = [0 0 200]
end
The above code works great - when I run the program it randomizes the color of an object between 4 different colors. However, I need code that randomizes the colors of another object so that if colour1 = [200 000 000], it will be one of the three available colors. I essentially need code that says something like colour2 (does not)= colour1, randomize the other three colors.
Any help would be very, very appreciated. :)

채택된 답변

Walter Roberson
Walter Roberson 2012년 11월 13일
colarray = [200 200 0; 200 0 0; 0 200 0; 0 0 200];
colidx1 = randi(4,1,1);
colour1 = colarray(colidx1,:);
colidx2 = randi(4,1,1);
while ismember(colidx2, colidx1)
colidx2 = randi(4,1,1);
end
color2 = colarray(colidx2,:);
colidx3 = randi(4,1,1);
while ismember(colidx3, [colidx1, colidx2])
.... and you should be able to finish from here
  댓글 수: 2
Brett
Brett 2012년 11월 13일
This worked beautifully. Thank you so much!
Walter Roberson
Walter Roberson 2012년 11월 13일
This can be improved quite a bit if you are willing to modify your variables slightly:
numobj = 4; %can be less than number of colors
colarray = [200 200 0; 200 0 0; 0 200 0; 0 0 200];
colidx = randperm(size(colarray,1));
colidx = colidx(1:numobj);
color = colarray(colidx, :);
And if you have one of the newer versions of MATLAB this can be reduced slightly:
numobj = 4; %can be less than number of colors
colarray = [200 200 0; 200 0 0; 0 200 0; 0 0 200];
colidx = randperm(size(colarray,1), numobj);
color = colarray(colidx, :);
These do not generate separate variables for the colors, they generate an array in which the rows correspond to the colors for the different objects.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 11월 13일
Why can't you just set the color of colour2 at the same time as when you set colour1, inside the if statements? Just set it to one of the other colors, one of the ones you didn't set colour1 to.
  댓글 수: 1
Brett
Brett 2012년 11월 13일
Because I planned on adding 4 different color combinations on four different objects. This would mean writing 254 different combinations... yikes.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by