Reputation: 457
Suppose I have a zero matrix of 75x50 where every zero will be replaced by the distance from some reference index in the matrix, such as every element having a pair of indexes (i, j) tells me the Euclidean distance from the reference point. So if the reference point is at (i = 25, j= 44), I need to compute the distance from every other 'i' and 'j' to this point. I could do this with a pair of loops but since my matrix is in reality much larger, I was wondering wether and how I can make this faster.
Thanks
Upvotes: 2
Views: 269
Reputation: 4768
One way to do this would be to use bsxfun
with the hypot
function. Like so:
rows = 75;
cols = 50;
i=25;
j=44;
bsxfun(@hypot, (1:rows)' - i, (1:cols) - j);
Essentially what this is doing is generating two matrices. One like this:
1 2 3 ... 50
1 2 3 ... 50
...
and the other like this:
1 1 1 ...
2 2 2
...
75 75 75
You can think of these as vector coordinates . We then subtract i
and j
from them so that the point equals zero, and every other point gives the distance from them in vector space (e.g. <-2,3>
). @hypot
then calculates the length of said vector (so, for instance, <-2,3>
would become 4.0). It does this for every element of the matrix, which then becomes your matrix of euclidean distances.
Note that this is probably not what is actually happening behind the scenes, but I find it's a useful way of thinking about it.
Upvotes: 2