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

3 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 22 Jan 2023
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 :)

Sign in to comment.

Accepted Answer

DGM
DGM on 22 Jan 2023
Edited: DGM on 22 Jan 2023
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

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!