Clear Filters
Clear Filters

If inside of for loop is not working

2 views (last 30 days)
Muhammad Senna
Muhammad Senna on 23 Aug 2022
Commented: Muhammad Senna on 23 Aug 2022
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?

Answers (1)

Chunru
Chunru on 23 Aug 2022
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]}

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!