Assign a set of values in a matrix depending on the index of it

5 次查看(过去 30 天)
I have two matrices from which I compute the distances between Points in P1 and P2. In P1, I have only X and Y coordinates.
P1=[12 45
34 7 ]
and in P2 , I have the index of the point (in the first column), X and Y coordinates. The index in the first column is not sorted and it is not complete. Like in the example, I don't have indices 1,4 and 5.
P2= [2 42 25
6 37 57
3 55 16]
So after computing the distances bw the points of P1 and P2, I have the result in another matrix D. Now, I have another matrix Dall, where I have rows for all points (from P2 and those not also into it). I want to put the distances I got from D inside of Dall for the corresponding rows.
What I am doing with a for loop is
for i=1:size(P1,1)
for j=1:size(P2,1)
x=P2(i,1);
Dall(x,j) = D(i,j);
end
end
Any more optimal way to do it?
  1 个评论
etudiant_is
etudiant_is 2016-3-18
编辑:etudiant_is 2016-3-18
If I do
Dall(P2(:,1),:)=4;
It works on the lines I want. But like this, it gives me an error.
Dall(P2(:,1),:)= D(:)

请先登录,再进行评论。

采纳的回答

etudiant_is
etudiant_is 2016-3-19
What worked for me is
Dall(P2(:,1),:)= D

更多回答(1 个)

Image Analyst
Image Analyst 2016-3-18
You didn't really say what you're doing to get D. So what I did, using pdist2() in the Statistics and Machine Learning Toolbox, is
P1 = [12 45
34 7 ]
P2 = [2 42 25
6 37 57
3 55 16]
distances = pdist2(P1, P2(:, 2:end))
I assume you did the same. So I got
distances =
36.0555127546399 27.7308492477241 51.8652099195598
19.6977156035922 50.0899191454728 22.8473193175917
The 2 rows correspond to the 2 points from P1, and the 3 columns are the distances to the corresponding 3 points in P2. But what I don't know is what you want Dall to look like.
  3 个评论
Image Analyst
Image Analyst 2016-3-18
Sorry, but we can't figure out the "rule" for how you distribute the numbers from distances into Dall.
etudiant_is
etudiant_is 2016-3-19
it is based on the value I have in the first column of P2. In this example I have 2, 6 and 3. So the first distance will be in line 2, the second in line 6 and the third in line 3 of Dall. I already found how to do it with
Dall(P2(:,1),:)= D
Thanks

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 NaNs 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by