I can't plot square or rectangle correctly
4 views (last 30 days)
Show older comments
x = input('enter x number:')
y = input('enter y number:')
z = input('enter widht:')
v = input('enter lenght:')
axes('NextPlot', 'add','XLim', [((-abs(x)-abs(z))+25), ((abs(x)+abs(z)+25))], 'YLim', [((-abs(y)-abs(v))+25), ((abs(y)+abs(v)+25))]);
for e = x:0.5:(abs(x)+abs(z))
plot(e, y, '*k')
pause(0.05)
end
for e = y:0.5:(abs(y)+abs(v))
plot(x,e, '*k')
pause(0.05)
end
for e = x:0.5:(abs(x)+abs(z))
plot(e,(abs(y)+abs(v)),'*k')
pause(0.05)
end
for e = y:0.5:(abs(y)+abs(v))
plot((abs(y)+abs(v)),e, '*k')
pause(0.05)
end
There is a issue with my last for-end loop. Last edge of rectangle doesn't fit correctly. Also I used 25 to see graph more clear. Can you check that. I feel like I did something wrong there too.
0 Comments
Accepted Answer
DGM
on 27 Mar 2021
Right off the bat, the xlim and ylim were way off in the weeds (at least for the parameters i chose). Try these changes:
% use meaningful descriptions
x = input('enter x offset: ')
y = input('enter y offset: ')
w = input('enter width: ')
h = input('enter height: ')
% filter these once instead of a bunch of times
w=abs(w);
h=abs(h);
clf
% here, i'm adding [h/2 w/2] margin around the box
% that's just something arbitrary i picked
axes('NextPlot', 'add','XLim', [x-w/2 x+w+w/2], 'YLim', [y-h/2 y+h+h/2]);
% why are you using abs(x) and abs(y) everywhere?
% that makes the size wrong if x or y is negative
% if x and y must be non-negative, filter them first, like with w and h
for e = x:0.5:(x+w)
plot(e, y, '*k')
pause(0.05)
end
for e = y:0.5:(y+h)
plot(x,e, '*k')
pause(0.05)
end
for e = x:0.5:(x+w)
plot(e,y+h,'*k')
pause(0.05)
end
for e = y:0.5:(y+h)
plot(y+h,e, '*k')
pause(0.05)
end
3 Comments
DGM
on 27 Mar 2021
Edited: DGM
on 27 Mar 2021
Auugh my bad. I was using unity aspect ratio, so I didn't catch that.
for e = y:0.5:(y+h)
plot(x+w,e, '*k')
pause(0.05)
end
If there are some odd requirements for calculating the plot area, then you'll have to follow whatever you're being told to use for calculating xlim and ylim. That said, if [y x] is the location of one corner and [y+h x+w] is the other corner, then you don't need abs() in the loops anywhere.
More Answers (0)
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!