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
0 个评论
回答(2 个)
Pawel Jastrzebski
2018-2-8
% '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
2018-2-8
This is rather strange:
M = zeros(mNumber,elements)
M(1:mNumber*elements) = ceil(6*rand(1,mNumber*elements))
M = randi(6,mNumber,elements)
Pawel Jastrzebski
2018-2-8
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 Center 和 File Exchange 中查找有关 NaNs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!