vector - Index an Array using values from a Matrix, Matlab -


this question has answer here:

i use values matrix index array. use 3x2 matrix in example matrix of height in actual code. array 5x5 in example square array of size. size of array , height of matrix have no relationship.

here 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 access points 2,1 4,3 , 1,4 , add 1 value in location.

i have tried following code

grid(x(:,1),x(:,2))=grid(x(:,1),x(:,2))+1 

which gives 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 not require. have tried other ways no luck, think use loop or create flat array don't want to, think there must more efficient way.

anyone have ideas? i'm using matlab 2012b.

as time , may able give.

edit-1 required result

this result

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, value in relative location in array (grid in example) show how many times coordinate occurs. solution is

grid(sub2ind(size(grid),x(:,1),x(:,2)))=grid(sub2ind(size(grid),x(:,1),x(:,2)))+1 

using answer 2d logical matrix vector of coordinates (basic matlab) oleg pointed me to. managed solve question converting subscripts linear indexes:

pos       = sub2ind(size(grid), x(:,1), x(:,2));  grid(pos) = 1; 

Comments