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

2 vues (au cours des 30 derniers jours)
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 commentaires
Fortia Alfeche
Fortia Alfeche le 22 Jan 2023
This is suppose to generate 66 combinations, but i'm getting less
Stephen23
Stephen23 le 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 :)

Connectez-vous pour commenter.

Réponse acceptée

DGM
DGM le 22 Jan 2023
Modifié(e) : DGM le 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

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by