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

4 ビュー (過去 30 日間)
Alexander Collins
Alexander Collins 2019 年 11 月 24 日
コメント済み: Alexander Collins 2019 年 11 月 24 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by