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 个评论

"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
"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 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!