I tried to generate a sequence with a specific interval, but the output skips some intervals.

1 回表示 (過去 30 日間)
mat = [];
interval = -0.10;
max = 1.00;
i = 0;
for a=1.00:interval:0.00
for b=1.00:interval:0.00
for c=1.00:interval:0.00
if a+b+c == max
mat(i+1,:) = [a,b,c];
i=i+1;
end
end
end
end
mat
  2 件のコメント
Fortia Alfeche
Fortia Alfeche 2023 年 1 月 22 日
This is suppose to generate 66 combinations, but i'm getting less
Stephen23
Stephen23 2023 年 1 月 22 日
Note that you can easily get rid of the loops:
mxv = 1;
[X,Y,Z] = ndgrid(0:0.1:1);
M = [X(:),Y(:),Z(:)];
M(abs(sum(M,2)-mxv)>1e-9,:) = []
M = 66×3
1.0000 0 0 0.9000 0.1000 0 0.8000 0.2000 0 0.7000 0.3000 0 0.6000 0.4000 0 0.5000 0.5000 0 0.4000 0.6000 0 0.3000 0.7000 0 0.2000 0.8000 0 0.1000 0.9000 0
And there are your 66 triples :)

サインインしてコメントする。

採用された回答

DGM
DGM 2023 年 1 月 22 日
編集済み: DGM 2023 年 1 月 22 日
I missed the comparison.
You're dealing with floating-point numbers. You can expect exact equality tests to fail due to rounding errors. This comment contains a number of links to related threads on the topic. Other people have explained it better than I can.
You can test for equality within some tolerance
mat = [];
interval = -0.10;
maxval = 1.00;
i = 0;
for a=1.00:interval:0.00
for b=1.00:interval:0.00
for c=1.00:interval:0.00
thissum = a+b+c;
if abs(thissum-maxval) < 1E-14
mat(i+1,:) = [a,b,c];
i=i+1;
end
end
end
end
mat
mat = 66×3
1.0000 0 0 0.9000 0.1000 0 0.9000 0 0.1000 0.8000 0.2000 0 0.8000 0.1000 0.1000 0.8000 0 0.2000 0.7000 0.3000 0 0.7000 0.2000 0.1000 0.7000 0.1000 0.2000 0.7000 0 0.3000

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by