필터 지우기
필터 지우기

If inside of for loop is not working

조회 수: 2 (최근 30일)
Muhammad Senna
Muhammad Senna 2022년 8월 23일
댓글: Muhammad Senna 2022년 8월 23일
This is my reference code, it is working well. g is a 96 x 1 cell.
k = 1;
dx = (65-45)/4; dy = 120/24;
y1 = 0; y2 = y1 + dy; x1 = 45; x2 = x1 + dx;
while y1 <= 120 && x2 <= 65
g{k} = [x1 x2 y1 y2];
y1 = y1 + dy; y2 = y2 + dy;
k = k + 1;
if y1 == 120
y1 = 0; y2 = y1 + dy; x1 = x1 + dx; x2 = x2 + dx;
end
end
g = g';
But this code does not give the correct answer, g should be a 40x1 cell but it gave me 11x1 cell
k = 1;
dx = (3-0)/4; dy = 1/10;
y1 = 0; y2 = y1 + dy; x1 = 0; x2 = x1 + dx;
while y1 <=1 && x2 <=3
g{k} = [x1 x2 y1 y2];
y1 = y1 + dy; y2 = y2 + dy;
k = k + 1;
if y1 == 1
y1 = 0; y2 = y1 + dy; x1 = x1 + dx; x2 = x2 + dx;
end
end
g = g';
Any idea where I did wrong?

답변 (1개)

Chunru
Chunru 2022년 8월 23일
k = 1;
dx = (3-0)/4; dy = 1/10;
y1 = 0; y2 = y1 + dy; x1 = 0; x2 = x1 + dx;
while y1 <=1 && x2 <=3
%[k, y1, x2]
g{k} = [x1 x2 y1 y2];
y1 = y1 + dy; y2 = y2 + dy;
k = k + 1;
% Due to the floating point rounding error, y1 == 1 is never be true
% for this code. Make change as follows:
if abs(y1 - 1) < 1e-10
y1 = 0; y2 = y1 + dy; x1 = x1 + dx; x2 = x2 + dx;
end
end
g = g'
g = 40×1 cell array
{[ 0 0.7500 0 0.1000]} {[ 0 0.7500 0.1000 0.2000]} {[ 0 0.7500 0.2000 0.3000]} {[ 0 0.7500 0.3000 0.4000]} {[ 0 0.7500 0.4000 0.5000]} {[ 0 0.7500 0.5000 0.6000]} {[ 0 0.7500 0.6000 0.7000]} {[ 0 0.7500 0.7000 0.8000]} {[ 0 0.7500 0.8000 0.9000]} {[ 0 0.7500 0.9000 1.0000]} {[ 0.7500 1.5000 0 0.1000]} {[0.7500 1.5000 0.1000 0.2000]} {[0.7500 1.5000 0.2000 0.3000]} {[0.7500 1.5000 0.3000 0.4000]} {[0.7500 1.5000 0.4000 0.5000]} {[0.7500 1.5000 0.5000 0.6000]}

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by