no repeating numbers in a matrix
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
Pawel Jastrzebski
le 8 Fév 2018
% '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 commentaires
Stephen23
le 8 Fév 2018
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
le 8 Fév 2018
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.
Voir également
Catégories
En savoir plus sur NaNs dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!