1

I would like to use values from a matrix to index an array. I will use a 3x2 matrix in the example but it could be a matrix of any height in the actual code. The array will be 5x5 in the example but could be a square array of any size. The size of the array and height of the matrix have no relationship.

Here is my code

X =

     2     1
     4     3
     1     4

Grid=zeros(5,5)

Grid =

     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0

So i would like to access points 2,1 4,3 and 1,4 and add one to the value in that location.

I have tried the following code

Grid(X(:,1),X(:,2))=Grid(X(:,1),X(:,2))+1

Which gives this result

Grid =

     1     0     1     1     0
     1     0     1     1     0
     0     0     0     0     0
     1     0     1     1     0
     0     0     0     0     0

Which is not what I require. I have tried other ways with no luck, I think i could use a loop or create a FLAT array but don't really want to, I think there must be a more efficient way.

Anyone have any ideas? I'm using Matlab 2012b.

As always thanks for your time and any help you may be able to give.

Edit-1 Required Result

This is the result I would like

Grid =

     0     0     0     1     0
     1     0     0     0     0
     0     0     0     0     0
     0     0     1     0     0
     0     0     0     0     0

Edit-2

The coordinate matrix may hold duplicate values, so I would like the value in the relative location in the Array (Grid in the example) to show how many times this coordinate occurs. So my solution is

Grid(sub2ind(size(Grid),X(:,1),X(:,2)))=Grid(sub2ind(size(Grid),X(:,1),X(:,2)))+1
user2519890
  • 157
  • 2
  • 14
  • or of http://stackoverflow.com/questions/17516031/matlab-matrix-containing-values-of-another-matrix-at-specific-indices/17516124#17516124 – Adiel Jul 11 '13 at 12:46
  • Yes it looks like it is a slight variation on http://stackoverflow.com/questions/8209686/2d-logical-matrix-from-vector-of-coordinates-basic-matlab, Thank you @OlegKomarov – user2519890 Jul 11 '13 at 12:51
  • @user2519890 if this is the case, you can delete this question. – Shai Jul 11 '13 at 12:52
  • @Shai it is a slight variation and i have answered this question, do you still recommend I delete it? – user2519890 Jul 11 '13 at 12:55
  • I finally prefer how this question is formulated to the potential 'original'. Therefore, on second thought I recommend voting this one and making it a reference. – Oleg Jul 11 '13 at 13:31

1 Answers1

0

Using the answer to 2D logical matrix from vector of coordinates (Basic matlab) that Oleg pointed me to. I managed to solve my question by converting subscripts to linear indexes:

pos       = sub2ind(size(Grid), X(:,1), X(:,2)); 
Grid(pos) = 1;
Community
  • 1
  • 1
user2519890
  • 157
  • 2
  • 14