indexing problem in a matrix.

조회 수: 8 (최근 30일)
cgo
cgo 2015년 11월 9일
답변: Walter Roberson 2015년 11월 9일
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.

답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by