2014-05-08 21 views
1

我需要我的代碼幫助。該代碼用於查找平方距離問題的minumin。我通過一個例子提供我的代碼,我相信這將是解釋我需要的最簡單的方法。找到組合矩陣的索引位置

clear all 
clc 
x=10.8; % is a fixed value 
y=34; % is a fixed value 
z=12; % is a fixed value 
A = [11 14 1; 5 8 18; 10 8 19; 13 20 16]; % a (4x3) matrix 
B = [2 3 10; 6 15 16; 7 3 15; 14 14 19]; % a (4x3) matrix 

我創造它在這下面的方式組成一個新的矩陣C

C1 = bsxfun(@minus, A(:,1)',B(:,1)); 
C1=C1(:); % this is the first column of the new matrix C 
C2 = bsxfun(@minus, A(:,2)',B(:,2)); 
C2=C2(:); % this is the second column of the new matrix C 
C3 = bsxfun(@minus, A(:,3)',B(:,3)); 
C3=C3(:); % this is the third column of the new matrix C 
C = [C1 C2 C3]; % the new matrix C of size (16x3) 

C有以這種方式形成!這就是我的意思,當我在我的標題組成的矩陣中寫道

然後:

[d,p] = min((C(:,1)-x).^2 + (C(:,2)-y).^2 + (C(:,3)-z).^2); 
d = sqrt(d); 
outputs: 
d = 18.0289; 
p = 13; 

讓我滿足該分鐘問題的距離(d)和位置(P) 。

我的問題: 我需要找到其中的A and B組合給了我這個p值,換句話說,我需要從'A,B'這給了我這個最佳C1,C2,C3指數:

C1 = bsxfun(@minus, A(?,1)',B(?,1)); 
C2 = bsxfun(@minus, A(?,2)',B(?,2)); 
C3 = bsxfun(@minus, A(?,3)',B(?,3)); 

?是索引位置我需要,在這種情況下,矩陣A的索引位置和B.

的我有以下說明的索引位置手工計算值:

我知道:

C = [9 11 -9 
5 -1 -15 
4 11 -14 
-3  0 -18 
3  5  8 
-1 -7  2 
-2  5  3 
-9 -6 -1 
8  5  9 
4 -7  3 
3  5  4 
-4 -6  0 
11 17  6 
7  5  0 
6 17  1 
-1  6 -3] 

我知道,我的最佳指數在第13位給出。該指數位置追溯到:

[13-2 20-3 16-10] 

這是A(4,:) - B(1,:)

我需要一個代碼,它可以幫助我找到從A這個指標和B提前

謝謝!

PS。我正在使用ODE的參數估計問題中的代碼。

+0

這令人困惑,從標量和矢量之間的距離開始。一個向量沒有一個位置,只有一個量級和一個方向。你的意思是你想找到1點和存儲在矢量中的一組點之間的最短距離?然後你談論矩陣'A'和'B'。鑑於點和矢量之間距離的某種定義,很難理解'A'和'B'代表什麼。第三,您應該在示例代碼中修復'z'中的錯誤。 – patrik

回答

1

第一種情況:向量矩陣情況下

subvals = bsxfun(@minus,A,[x y z]) 
[distance,index] = min(sqrt(sum(subvals.^2,2))) 

第二種情況:兩個矩陣的情況下

subvals = bsxfun(@minus,A,permute(B,[3 2 1])); 
[distances,indices] = min(sqrt(sum(subvals.^2,2)),[],3) 

測試對於第二種情況:

%%// Get some random data into A and B 
A = randi(20,8,3) 
B = randi(20,4,3) 

%%// Just to test out out code for correctness, 
%%// let us make any one one row of B, say 3rd row equal to 
%%// any one row of A, say the 6th row - 
B(3,:) = A(6,:) 

%%// Use the earlier code 
subvals = bsxfun(@minus,A,permute(B,[3 2 1])); 
[distances,indices] = min(sqrt(sum(subvals.^2,2)),[],3) 

%%// Get the minimum row index for A and B 
[~,min_rowA] = min(distances) 
min_rowB = indices(min_rowA) 

驗證

min_rowA = 
    6 

min_rowB = 
    3 

編輯1響應張貼在的問題簡單的例子]:

標題說,你有興趣在尋找兩個矩陣的差異,然後找到它之間的最短距離到矢量[xyz]。所以,我希望這是你所需要的 -

x=10.8; 
y=34; 
z=12; 
A = [11 14 1; 5 8 18; 10 8 19; 13 20 16]; 
B = [2 3 10; 6 15 16; 7 3 15; 14 14 19]; 

C = A -B; %%// Distance of two vectors as posted in title 
subvals = bsxfun(@minus,C,[x y z]) 
[distance,index] = min(sqrt(sum(subvals.^2,2))) 

輸出

distance = 
    31.0780 

index = 
    3 

編輯2:當你這樣做之後 -

[d,p] = min((C(:,1)-x).^2 + (C(:,2)-y).^2 + (C(:,3)-z).^2); 

如果你正在尋找找到A和B的相應指標,你可以這樣做 -

[minindex_alongB,minindex_alongA] = ind2sub(size(A),p)