Matthew R
Matthew R

Reputation: 232

Accessing Matrix Elements by a "List of Points"

I have some large matrices of data, and a a two column matrix containing x and y locations, is there an easier way to work with the data elements corresponding to those points then:

for adj = 1:size(loc,1)
    testFunc(data1(loc(i,2),loc(i,1)), data2(loc(i,2),loc(i,1)), othervals)
end

Mostly I'm looking for a way to access the data elements by something closer to data1(loc(i))

Upvotes: 2

Views: 2037

Answers (2)

Jonas
Jonas

Reputation: 74940

What you want is to access elements of data via their linear indices. Linear indices increment first along the first dimension, then along the second dimension, and so on. For example the elements of a 3-by-2 array would be addressed in the following order

1 3 5
2 4 6

So to get element (2,1) of a 2-by-3 array via linear indexing, you would call array(3). To convert between linear index and subscripts (such as the pair 2,3), you can use ind2sub and sub2ind, respectively.

In your case, you'd run

linIdx = sub2ind(size(data),loc(:,2),loc(:,1))

if the first column of loc indexes into columns of data, and the second column of loc indexes into rows.

Then you can loop over linIdx to change your function call inside the loop to

testFunc(data1(linIdx(i)), data2(linIdx(i)), othervals)

Upvotes: 4

Oli
Oli

Reputation: 16035

You can convert the x-y location into indices, and the use the indices to adress the matrix. Then you can use arrayfun, to pally that your function to all elements.

ind=sub2ind(size(data1),location(:,1),location(:,2));
output=arrayfun(@(x,y) testFunc(x,y,othervals),data1(ind),data2(ind));

or if testFunc does not output a scalar:

output=arrayfun(@(x,y) testFunc(x,y,othervals),data1(ind),data2(ind),'UniformOutput',0);

Upvotes: 1

Related Questions