MATLAB Answers

0

Drawpolygon starting at a certain point ?

Asked by mohammad ibrahim on 23 Apr 2019
Latest activity Edited by Adam Danz
on 15 May 2019 at 21:36
Hello
I would like to use the function drawpolygon() to start an interactive plot , but I want to oblige the users to always start at the point (0,0) , and also to limit the nmber of vertices to 8 ? can I do this using drawpolygon() ?
I am using R2018b
many thanks
Mike

  0 Comments

Sign in to comment.

1 Answer

Answer by Adam Danz
on 23 Apr 2019
Edited by Adam Danz
on 15 May 2019 at 21:36

The starting coordinate and number of vertices cannot be controlled by drawpolygon(). However, you can control whether the polygon created by the user is accepted or not.
In this script, instructions are displayed below the main axes. The user must start at (0,0) and there must be 8 vertices. In reality, it's virtually impossible to manually select (0.000, 0.000) so if the user starts "near" to (0,0) (with less than 0.1 error in x or y directions), the starting coordinate is accepted. If the user starts outside of that threshold, or if the user selects more or less vertices than 8, the polygon will be deleted and the user will have to start over. If they obey those two requirements, the polygon is first shifted to the true (0,0) starting point and then the shape is accepted.
Play around with this functional example and you can tweek it to your needs.
%Set up figure
fh = figure;
axh = axes('Position', [.13 .18 .78 .73]); %main axes
axhTxt = axes('Position', [.13 .01 .78 .12], 'Visible', 'Off'); %instructions axis
grid(axh, 'on')
xlim(axh, [-5 5])
ylim(axh, [-5 5])
% draw polygon
nVertices = 8; %number of vertices
instructions = sprintf('Draw %d vertices. The first one should be at (0,0).', nVertices);
th = text(axhTxt, .5, .5, instructions, ...
'VerticalAlignment', 'Middle', 'HorizontalAlignment', 'Center');
userFailed = true; %initial loop flag
while userFailed && isvalid(fh)
h = drawpolygon(axh);
% Determine whether the user obeyed instructions
% It's impossible to manually select (0,0). Here we test that the user was "close enough" to accept
% the coordinate and then we shift the whole polygon to (0,0) if accepted.
maxError = 0.1; % max allowed error
userFailed = isvalid(fh) && ((size(h.Position,1) ~= nVertices) || (any(h.Position(1,:) >= maxError)));
if ~userFailed && isvalid(fh)
% User obeyed instructions.
h.Position = h.Position - h.Position(1,:); %shift polygon so first point is at true (0,0)
th.String = 'Good job.'; %to delete instead: delete(th)
elseif userFailed && isvalid(fh)
% User didn't obey instructions
delete(h)
th.String = sprintf('Try again! %s', instructions);
end
end

  1 Comment

hello. very nice idea. thank you

Sign in to comment.