2

I have a 2D vector which contains the coordinates which I want to represent as True or one in a matrix with dimensions nxm. Can I build this matrix without a loop?

Currently I am doing this:

points = [(1,1), (30, 20), (8,7)]
grid = zeros(n,m);

for i = 1:length(points)
    grid(points(i,1),points(i,2))=1;
end

Thanks a lot I'm newbie in matlab and I couldn't find the answer so far.

rauldg
  • 401
  • 4
  • 17

2 Answers2

6

I recommend using a sparse matrix if the number of coordinates (length(points)) is much smaller (<10%) than n*m. This will make better use of memory and save you time.

points=[1,30,8;1,20,7];
grid = sparse(points(1,:), points(2,:), 1, n ,m);
cyborg
  • 9,989
  • 4
  • 38
  • 56
3

Your assignment to points is syntactically incorrect, it should be:

points=[1,30,8;1,20,7];

The solution to you problem lies in converting subscripts to linear indices with sub2ind:

grid(sub2ind(size(grid),points(1,:),points(2,:)))=1
jpjacobs
  • 9,359
  • 36
  • 45