我想计算n通道矩阵的每个元素之间的欧式距离,然后将函数exp(-dist)
应用于它。我的矩阵是MxN,因此输出必须是(MxN)x(MxN)。
到目前为止,这是我的代码:
MAX=M*N;
A = zeros([MAX,MAX]);
dist= zeros([MAX,MAX]);
for x1=1:MAX
for x2=1:MAX
for i=1:M
for j=1:N
for s=1:M
for z=1:N
%every pixel is a vector rgb
dist(x1,x2) = norm((imIn(i,j)-imIn(s,z)),3);
A(x1,x2) = exp(-dist);
end
end
end
end
end
end
这真的很慢,而且不起作用-它只能给出一个。
答案 0 :(得分:0)
我会使用bsxfun:
*请注意,由于距离是应用于标量值的,因此我仅使用abs(a-b)。调用norm()没有意义,只是停滞时间。
m = 3;
n = 4;
ImIn = rand(m,n)
% first transform to vector
vector = ImIn(:)
% edit: better solution for older versions, see comments
Distances = abs(bsxfun(@minus, vector', vector))
% for latest matlab versions
Distances = abs(vector'- vector)
输出:
ImIn =
0.5833 0.9747 0.6369 0.6378
0.4217 0.2235 0.6486 0.4072
0.6525 0.1869 0.2085 0.5017
vector =
0.5833
0.4217
0.6525
0.9747
0.2235
0.1869
0.6369
0.6486
0.2085
0.6378
0.4072
0.5017
Distances =
0 0.1616 0.0693 0.3915 0.3597 0.3964 0.0536 0.0654 0.3747 0.0546 0.1761 0.0816
0.1616 0 0.2308 0.5530 0.1982 0.2348 0.2152 0.2269 0.2132 0.2161 0.0145 0.0800
0.0693 0.2308 0 0.3222 0.4290 0.4656 0.0156 0.0039 0.4440 0.0147 0.2453 0.1508
0.3915 0.5530 0.3222 0 0.7512 0.7879 0.3379 0.3261 0.7662 0.3369 0.5675 0.4731
0.3597 0.1982 0.4290 0.7512 0 0.0366 0.4134 0.4251 0.0150 0.4143 0.1837 0.2782
0.3964 0.2348 0.4656 0.7879 0.0366 0 0.4500 0.4618 0.0217 0.4509 0.2203 0.3148
0.0536 0.2152 0.0156 0.3379 0.4134 0.4500 0 0.0117 0.4284 0.0009 0.2297 0.1352
0.0654 0.2269 0.0039 0.3261 0.4251 0.4618 0.0117 0 0.4401 0.0108 0.2414 0.1469
0.3747 0.2132 0.4440 0.7662 0.0150 0.0217 0.4284 0.4401 0 0.4293 0.1987 0.2932
0.0546 0.2161 0.0147 0.3369 0.4143 0.4509 0.0009 0.0108 0.4293 0 0.2306 0.1361
0.1761 0.0145 0.2453 0.5675 0.1837 0.2203 0.2297 0.2414 0.1987 0.2306 0 0.0945
0.0816 0.0800 0.1508 0.4731 0.2782 0.3148 0.1352 0.1469 0.2932 0.1361 0.0945 0
检查:
>> size(ImIn)
ans =
3 4
>> size(Distances)
ans =
12 12