How to create a grid of evenly spaced ones in a matrix of zeros?

2 次查看(过去 30 天)
So essentially I want a grid looking something like this:
0 0 0 0 0 0
0 1 0 0 1 0
0 0 0 0 0 0
0 1 0 0 1 0
0 0 0 0 0 0
or something similar, with flexibility in the number of ones and how they're distributed, and the size of the matrix.
This is what I currently have:
u = 1:500; % size of matrix
v = u;
[u, v] = meshgrid(u, v);
N_points = 5; %number of points in each axis
point_array = zeros(size(u));
pos_x = round(size(u,1)/2) + separation_x * (-(N_points-1)/2:(N_points-1)/2); % positioning of points
pos_y = round(size(u,2)/2) + separation_y * (-(N_points-1)/2:(N_points-1)/2);
[pos_x,pos_y] = meshgrid(pos_x,pos_y);
point_array(sub2ind(size(point_array),pos_x,pos_y)) = 1; % converts x/y coordinates of chosen points into index of corresponding point in matrix, sets equal to 1.
Is there a more compact or straightforward way to achieve this?

采纳的回答

Guillaume
Guillaume 2019-11-24
"Is there a more compact or straightforward way to achieve this?"
Definitively!
%demo data
size_array = 500;
npoints = 15;
point_array = zeros(size_array); %create array full of zeros
locations = linspace(0, size_array, npoints+1); %calculate location with one more point to get the spacing right
locations = round(locations(2:end) - locations(2)/2); %then remove first point (0) and offset by half the distance to 2nd point
point_array(locations, locations) = 1; %and set these locations to 1
%for visualisation
imagesc(point_array); axis('square'); colormap(gray)
  1 个评论
Alexander Collins
Alexander Collins 2019-11-24
Thanks, this works. Although the method I orignally posted generates the points relative to the centre, with a constant offset, and so keeps the grid symmetric with respect to the matrix.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by