Is it possible to insert a polyshape onto an already defined grid?

5 views (last 30 days)
Hi,
If i already have a 10x10 grid (say ranging from 1:10 in both x and y) and I create a triangle (lets say a side length of 2) using polyshape (or other) is there a way to impose the triangle onto the already preestablished grid? The aim is to have a grid where I can place objects and have greater ability of manipulating them such as rotating them.
Currently im using loops to make the triangle on the pre-established grid, but I have no control of its rotation.
If there is a better way of going about this then please let me know!

Answers (1)

VINAYAK LUHA
VINAYAK LUHA on 24 Nov 2023
Hi Johnny,
I understand that you want to insert a polyshape onto a preestablished grid in MATLAB and further you also want to manipulate the shape's position and orientation in the grid.
Follow the below steps to plot a triangle using the "polyshape" function in a grid and manipulate its position and orientation using arrow keys.
  1. Create a grid using the "meshgrid" function.
  2. Define the vertices of the triangle and create a polyshape of the triangle providing the vertices of the triangle as input to the "polyshape" function.
  3. Create a figure and plot the defined grid and triangle.
  4. Attach a callback function to the created figure, say "KeyPressFcn" to capture key press events on the figure.
  5. Implement the "KeyPressFcn" such that -
  • It identifies the key presses and configures the corresponding action to perform.
  • An Action takes the current polyshape object as input and modifies its vertices as per pre-defined transformation.
  • Clear the current figure and replot the modified polyshape to it.
Here is the detailed code snippet to implement the above instructions-
global x;
global y;
[x, y] = meshgrid(1:10, 1:10);
triangleVertices = [3 3; 5 3; 4 5];
global triangle
triangle = polyshape(triangleVertices);
figure;
plot(x, y, 'k.');
hold on;
plot(triangle);
set(gcf, 'KeyPressFcn', @keyPressed);
function keyPressed(~, event)
global triangle
step = 0.1;
switch event.Key
case 'uparrow'
triangle = translate(triangle, [0, step]);
case 'downarrow'
triangle = translate(triangle, [0, -step]);
case 'leftarrow'
triangle = rotate(triangle, deg2rad(20), mean(triangle.Vertices));
case 'rightarrow'
triangle = rotate(triangle, deg2rad(-20), mean(triangle.Vertices));
end
clf;
global x;
global y;
plot(x, y, 'k.');
hold on;
plot(triangle);
end
Additionally, refer to the following documentations for more details on how to use the above-mentioned functions-
Hope this helps you in understanding how to insert a polyshape onto a pre-established grid in MATLAB and further manipulate its position and orientation.
Best regards,
Vinayak Luha

Categories

Find more on Elementary Polygons in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!