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

4 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Guillaume
Guillaume am 24 Nov. 2019
"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 Kommentar
Alexander Collins
Alexander Collins am 24 Nov. 2019
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by