no repeating numbers in a matrix

1 回表示 (過去 30 日間)
Lucas Berghmans
Lucas Berghmans 2018 年 2 月 8 日
コメント済み: Pawel Jastrzebski 2018 年 2 月 8 日
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
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
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
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 ExchangeNaNs についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by