Recording variables that satisfy a condition
3 ビュー (過去 30 日間)
古いコメントを表示
Typical new matlab user here, so just looking for help and to learn, I know this is probably a simple question.
Basically, I have three variables X, Y, and Z that span from 0 to 1 spaced by 100. I want to record all instances where X + Y + Z = 1. This is what I have so far:
X = linspace(0,1,100);
Y = linspace(0,1,100);
Z = linspace(0,1,100);
poss = zeros(1000,3); %just a space to populate answers
for i = 1:100
for j = 1:100
for k = 1:100
p = X(i)+Y(j)+Z(k);
if p==1
poss(i,1)=X(i);
poss(i,2)=Y(j);
poss(i,3)=Z(k);
end
end
end
end
Am I on the right track? I just want to record the three variables X, Y, and Z in three columns if their sum totals to one. This is part of a more complex problem but I tried to simplify it. Thanks
2 件のコメント
Stephen23
2021 年 1 月 28 日
編集済み: Stephen23
2021 年 1 月 29 日
"Am I on the right track?"
Probably not, unless as a self-declared "new matlab user" you already have a good practical understanding of binary floating point numbers. The answers below also do not take into account floating point error, e.g. madhan ravi's answer does not include this combination (and many others):
V = linspace(0,1,100);
V(2)
V(98)
1-V(2)-V(2)-V(98)
Given the essentially arbitrary rounding of these floating point sums, the task of selecting only those that happen to add to exactly one does not seem to be very meaningful. Or are you performing some floating point magic?
採用された回答
madhan ravi
2021 年 1 月 28 日
X = linspace(0,1,100);
Y = linspace(0,1,100);
Z = linspace(0,1,100);
[XX, YY, ZZ] = meshgrid(X, Y, Z);
XYZ = XX + YY + ZZ;
Pass(:, 3) = ZZ(XYZ == 1);
Pass(:, 2) = YY(XYZ == 1);
Pass(:, 1) = XX(XYZ == 1);
Pass
0 件のコメント
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!