no repeating numbers in a matrix

1 次查看(过去 30 天)
I'm trying to find a method to shorten the code below. It take a lot of time to make it for more numbers, so I want to find something shorter and easier.
function y= example
m1=zeros(1,3);
m1(1,1)=ceil(6*rand);
m1(1,2)=ceil(6*rand);
m1(1,3)=ceil(6*rand);
m2=zeros(1,3);
m2(1,1)=ceil(6*rand);
m2(1,2)=ceil(6*rand);
m2(1,3)=ceil(6*rand);
while m1(1,2)==m1(1,1); m1(1,2)=ceil(6*rand); end
while m1(1,3)==m1(1,2)||m1(1,3)==m1(1,1); m1(1,3)=ceil(6*rand); end
while m2(1,1)==m1(1,3)||m2(1,1)==m1(1,2)||m2(1,1)==m1(1,1); m2(1,1)=ceil(6*rand); end
while m2(1,2)==m2(1,1)||m2(1,2)==m1(1,3)||m2(1,2)==m1(1,2)||m2(1,2)==m1(1,1); m2(1,2)=ceil(6*rand); end
while m2(1,3)==m2(1,2)||m2(1,3)==m2(1,1)||m2(1,3)==m1(1,3)||m2(1,3)==m1(1,2)||m2(1,3)==m1(1,1); m2(1,3)=ceil(6*rand); end
disp(['m1 is :', num2str(m1)]) disp(['m2 is :', num2str(m2)])
end

回答(2 个)

Stephen23
Stephen23 2018-2-8
编辑:Stephen23 2018-2-8
Your approach is extremely inefficient. Just use randperm:
>> V = randperm(6);
>> m1 = V(1:3)
m1 =
4 2 5
>> m2 = V(4:6)
m2 =
6 1 3

Pawel Jastrzebski
% 'mNumber' - number of 'm's'
% 'elements' - number of elements in each 'm'
mNumber = 2;
elements = 3;
M = zeros(mNumber,elements)
M(1:mNumber*elements) = ceil(6*rand(1,mNumber*elements))
% I don't get your 'While' loop.
% But if you want to carry out operation that involves
% i.e the 'current element' in the row and the 'next one'
% Use vectors.
% i.e check if next element is the same as the current one
mNumberNEW = 5;
elementsNEW = 8;
Mnew = zeros(mNumberNEW,elementsNEW)
Mnew(1:mNumberNEW*elementsNEW) = ceil(6*rand(1,mNumberNEW*elementsNEW))
currentElement = 1:elementsNEW-1
nextElement = 2:elementsNEW
Mcomparison = Mnew(:,nextElement)== Mnew(:,currentElement)
  2 个评论
Stephen23
Stephen23 2018-2-8
This is rather strange:
M = zeros(mNumber,elements)
M(1:mNumber*elements) = ceil(6*rand(1,mNumber*elements))
It would be much simpler to just call randi:
M = randi(6,mNumber,elements)
Pawel Jastrzebski
True. I didn't have time to properly loop up the doc for 'rand'/'randi' and left the code at the first thing that came to my head that worked.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 NaNs 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by