用Matlab中的数组操作 [英] Operations with arrays in Matlab
问题描述
我有这个2维数组
x=[62,29,64;
63,31,62;
65,29,60;
63,29,62;
63,31,62;];
在每列中第1元素为R,第2是G,第3次是从下面的式B
1st element in each column is R, 2nd is G, 3rd is B from the formula below.
我想一个函数来计算如下操作:
I would like a function to compute the following operation:
到目前为止,我的函数的定义是这样的:
So far, my function definition looks like this:
function[distance]=RGB_dist(x,y)
distance=sqrt(sum(((x-y)*[3;4;2]).^2,2));
end
与上面的矩阵, DISP(RGB_dist(X,X))
只输出零测试。这一定会发生,因为他同样计算向量之间的距离。我该怎么做,从我的矩阵计算任意两个向量(线)之间的距离。任何帮助将是AP preciated。
Tested with the matrix above, disp(RGB_dist(x,x))
outputs only zeroes. That must happen because he is calculating the distance between same vectors. How do I do to calculate the distance between any two vector(lines) from my matrix. Any help would be appreciated.
推荐答案
有关两个任意线(例如1号线和2号线)做的:
For two arbitrary lines (e.g. line 1 and line 2) do:
RGB_dist(x(1,:), x(2,:))
如果你希望所有的组合,然后检查 pdist2
。如果你不具备统计工具箱(即没有 pdist2
),然后使用 nchoosek
以创建对所有可能的行
if you want all the combinations then check out pdist2
. If you don't have the stats toolbox (i.e. no pdist2
) then use nchoosek
to create all possible pairs of rows:
I = nchoosek(1:size(x,1),2);
D = RGB_dist(x(I(:,1),:), x(I(:,2),:))
顺便说一句,如果你想使用 pdist
或 pdist2
那么你将不得不改变你的功能能够找到一个观测和观察的一次性列表之间的距离。最简单的方法是,以取代 -
与 bsxfun
是这样的:
by the way, if you want to use pdist
or pdist2
then you will have to alter your function to be able to find the distance between one observation and a list of observations in one shot. The easiest way is to replace your -
with bsxfun
like this:
sqrt(sum(((bsxfun(@minus,x,y))*[3;4;2]).^2,2));
那么你可以去
D = pdist(x, @RGB_dist)
这两种方法给你。
both methods give you
D =
7
1
1
7
6
8
0
2
6
8
或
squareform(D)
ans =
0 7 1 1 7
7 0 6 8 0
1 6 0 2 6
1 8 2 0 8
7 0 6 8 0
不过,这可能是错误的,因为通过权重相乘后,这个广场。你可能不希望出现这种情况,所以我觉得你的最终功能应该看起来像在Divakar的答案
But this is probably wrong as this squares after multiplying by the weights. You probably don't want that so I think your final function should look like that in Divakar's answer
这篇关于用Matlab中的数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!