MATLAB Answers

How to obtain vertices of all smaller squares in a large square?

2 views (last 30 days)
Hi all,
I am going to generate a square map of side length rs and then divide it up into smaller squares of side length dc using meshgrid. Refer to the image and code below.
coord = 0:dc:rs;
[X,Y] = meshgrid(coord);
How would I obtain the vertices of all smaller squares? Some sort of combination of X and Y must have them but I would like that a new matrix XV is an Nx5 matrix with the x-coordinates of the squares and a matrix YV is an Nx5 matrix with the y-coordinates of the squares. Each row of each matrix would correspond to a different square where N is the number of squares. Also, columns = 5 to duplicate the first column so the vertices are closed and can be used for the inpolygon function.

Accepted Answer

Jonathan Mayers
Jonathan Mayers on 27 Sep 2016
I have achieved what I wanted with the following code.
function [ XV, YV ] = gen_clusters( rs,dc,X )
%GEN_CLUSTERS Generates the vertices of every cluster in the network.
%Input: rs - Side length of network
% dc - Side length of cluster
% X - Matrix X from meshgrid
%Output: XV - x-coordinates of clusters
% YV - y-coordinates of clusters
%XV and YV are nx5 matrices where n is the number of clusters. 5 columns
%are needed because the 5th column closes the cluster.
% Calculate no. of clusters
n = rs/dc;
% Preallocate
XV = zeros(n,4);
% Calculate XV
for i = 1:n
XV(i,:) = [repmat(X(1,i),1,2) repmat(X(1,i+1),1,2)];
% Calculate YV based on XV
YV = repmat(XV,n,1);
YV = circshift(YV,[0 -1]);
YV(:,5) = YV(:,1);
% Duplicate rows of XV n times
XV = reshape(repmat(XV(:)',n,1),[],4);
XV(:,5) = XV(:,1);

Community Treasure Hunt

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

Start Hunting!

Translated by