If inside of for loop is not working
2 views (last 30 days)
Show older comments
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?
0 Comments
Answers (1)
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'
See Also
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!