indexing problem in a matrix.

1 view (last 30 days)
cgo
cgo on 9 Nov 2015
Answered: Walter Roberson on 9 Nov 2015
I have n particles scattered in space. I measured the distances of all the particles relative to all the other particles by giving the following code:
for i = 1:n
for j = 1:n
matrix(i:j) = distance_function(i,j)
end
end
I now have an n by n symmetric matrix with the main diagonal zero. (because the distance of the i-th particle to itself is zero. and symmetric, because the distance from first to second particle is the same as second to first particle.)
Let's say for example I have the following distance matrix:
matrix = [0 1 1 2;
1 0 3 1;
1 3 0 2;
2 1 2 0]
Now, I want to see which of these particles are within a distance of, lets say for fun: 3, from anyone else.I will be moving them because of a force of repulsion.
This means that for particle 1: those that will contribute to the repulsion are: particles 2, 3, 4. repulsion of 2 is due to: 1, 4. repulsion of 3 is due to: 1 ,4. repulsion of 4 is due to 1, 2, 3.
How do I say this in Matlab? idx = find(matrix < 3 & matrix ~=0) gives you the indices linearly (in this case from 1 to 16.) It is difficult to pinpoint which particle contributes to which.
Please help.

Answers (1)

Walter Roberson
Walter Roberson on 9 Nov 2015
[r,c] = ind2sub(size(matrix), idx);
now r(K), c(K) are row/column pair versions of idx

Categories

Find more on Mathematics in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!