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

2 次查看(过去 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 个评论
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 CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by