I got global A, B, C, D, E, F, G, H, I. And they are all 2*1 matrix. And I would like to set random values for them.(Random values are between 2~14 for (1,1) of those matrices, and 1~4 for (1,2) of those matrices.) And also I would like to make all of them different each other.
I tried like this,
A = [ randi([2 14]); (randi(4)) ]
B = [ randi([2 14]); (randi(4)) ]
C = [ randi([2 14]); (randi(4)) ]
D = [ randi([2 14]); (randi(4)) ]
E = [ randi([2 14]); (randi(4)) ]
F = [ randi([2 14]); (randi(4)) ]
G = [ randi([2 14]); (randi(4)) ]
H = [ randi([2 14]); (randi(4)) ]
I = [ randi([2 14]); (randi(4)) ]
while A == B | A == C | A == D | A == E | A == F | A == G | A == H | A == I | B == C | B == D | B == E | B == F | B == G | B == H | B == I | C == D | C == E | C == F | C == G | C == H | C == I | D == E | D == F | G == G | D == H | D == I | E == F | E == G | E == H | E == I | F == G | F == H | F == I | G == H | G == I | H == I
A = [ randi([2 14]); (randi(4)) ]
B = [ randi([2 14]); (randi(4)) ]
C = [ randi([2 14]); (randi(4)) ]
D = [ randi([2 14]); (randi(4)) ]
E = [ randi([2 14]); (randi(4)) ]
F = [ randi([2 14]); (randi(4)) ]
G = [ randi([2 14]); (randi(4)) ]
H = [ randi([2 14]); (randi(4)) ]
I = [ randi([2 14]); (randi(4)) ]
end
But it never stops! Even all matrices(A, B, C, D, E, F, G, H, I) are different each other. What is wrong with this? Help me Plz

댓글 수: 1

Stephen23
Stephen23 2017년 12월 9일
"I got global A, B, C, D, E, F, G, H, I..."
Do not use global variables. Pass values properly between workspaces to make your code more efficient and much easier to debug. Globals are how people write ugly spaghetti code that is impossible to debug.

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

 채택된 답변

Stephen23
Stephen23 2017년 12월 9일
편집: Stephen23 2017년 12월 9일

0 개 추천

"What is wrong with this?"
Too many variables. Beginners sometimes want to store their data in lots of separate variables, but in fact data should be kept together as much as possible because it makes processing that data much simpler and more efficient. You would be much better off using just one array to hold all of those, which would make the code much simpler:
N = 9;
fun = @(r)[randi([2,14],r,1),randi([1,4],r,1)];
arr = fun(N);
while size(unique(arr,'rows'),1)<N
arr = fun(N);
end
Giving one matrix where each row is guaranteed unique:
>> arr
arr =
3 3
10 2
13 3
6 1
14 1
12 3
11 4
8 3
8 4
Did you see what I did there? By using better data design (i.e. keeping the data in one variable) I turned your twenty lines of complex and non-working code into five lines of code that actually work.
Note that it would also be possible to only replace the duplicated rows, which would be more efficient if the likelihood of getting duplicate rows was high.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2017년 12월 9일

편집:

2017년 12월 9일

Community Treasure Hunt

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

Start Hunting!