no repeating numbers in a matrix

1 vue (au cours des 30 derniers jours)
Lucas Berghmans
Lucas Berghmans le 8 Fév 2018
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

Réponses (2)

Stephen23
Stephen23 le 8 Fév 2018
Modifié(e) : Stephen23 le 8 Fév 2018
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
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
Stephen23 le 8 Fév 2018
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
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.

Connectez-vous pour commenter.

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!

Translated by