for文・if文を用いて、条件を満たすパターンの組み合わせを出したい
11 views (last 30 days)
Show older comments
MATLAB初心者で手も足も出ないので、教えてください。
【やりたいこと】
条件を満たすような5つの変数のパターンの組み合わせを出したい。
任意の値:N=〇
変数:Za、Zb、Zc、Zd、Ze (全て整数で、値は5~150の範囲)
条件:Zc/Za>1
(Zb・Ze)/(Zc・Zd)>1
(Zb・Ze)/(Za・Zd)>1
X=(Za+Zc)/N (整数)
Y=(Za・Zd+Zb・Ze)/(N・(ZbとZdの最大公約数)) (整数)
Z=(Zc・ZdーZb・Ze)/(N・(ZbとZdの最大公約数)) (整数)
出力イメージとしては、
(Za、Zb、Zc、Zd、Ze)=(11、11、34、12、38)
(10、32、30、74、72)
・
・
・
よろしくお願いします。
Accepted Answer
交感神経優位なあかべぇ
on 16 Dec 2022
forとifを使って、素直に実装しようとすると、下記のようになりますかね。ただ、これだといつまで経っても処理が終わらないので、パフォーマンスを改善した実装が必要になると思います。
(ちなみにZ=(Zc・ZdーZb・Ze)/(N・(ZbとZdの最大公約数)) (整数)の条件のZcはZcでいいですかね?(コメントのコード文ではZcではなくZaだったので、どちらかが書き間違えかなと))
N = 5; % ピニオンの歯数
A = zeros(0, 5);
for Za = 5 : 150
for Zb = 5 : 150
for Zc = 5 : 150
for Zd = 5 : 150
for Ze = 5 : 150
if ~(Zc / Za > 1)
continue;
end
if ~((Zb * Ze) / (Zc * Zd) > 1)
continue;
end
if ~((Zb * Ze) / (Za * Zd) > 1)
continue;
end
X = (Za + Zc) / N;
if ~(X == floor(X))
continue;
end
Q = gcd(Zb, Zd);%ZbとZdの最大公約数
Y = (Za * Zd + Zb * Ze) / (N * Q);
if ~(Y == floor(Y))
continue;
end
Z = (Zc * Zd - Zb * Ze) / (N * Q);
if ~(Z == floor(Z))
continue;
end
A(end + 1, :) = [Za, Zb, Zc, Zd, Ze];
end
end
end
end
end
A % 結果の表示
上記コードの途中までの結果の答え

More Answers (1)
Hernia Baby
on 16 Dec 2022
まずはデータを用意
N = 1;
Z = randi([5 150],5000,5);
Za = Z(:,1);
Zb = Z(:,2);
Zc = Z(:,3);
Zd = Z(:,4);
Ze = Z(:,5);
条件を作る
idx1 = Zc./Za > 1;
idx2 = (Zb.*Ze)./(Zc.*Zd)>1;
idx3 = (Zb.*Ze)./(Za.*Zd)>1;
X = (Za+Zc)./N;
Y = (Za.*Zd+Zb.*Ze)./(N.*gcd(Zb,Zd));
Z = (Zc.*Zd-Zb.*Ze)./(N.*gcd(Zb,Zd));
% 整数か判定
idx4 = X == floor(X);
idx5 = Y == floor(Z);
idx6 = Z == floor(Z);
全てを満たす条件
idx = idx1 & idx2 & idx3 & idx4 & idx5 & idx6;
条件に合うものを抽出
Z(idx,:)
See Also
Categories
Find more on ソルバー出力と反復表示 in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!