필터 지우기
필터 지우기

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

조회 수: 3 (최근 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 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