MATLAB向量化 [英] MATLAB vectorize
问题描述
我想知道是否有人可以帮助我将这段代码向量化.
I was wondering if anyone could help me vectorize this piece of code.
fr_bw是一个矩阵.
fr_bw is a matrix.
for i=1:height
for j=1:width
[min_w, min_w_index] = min(w(i,j,:));
mean(i,j,min_w_index) = double(fr_bw(i,j));
sd(i,j,min_w_index) = sd_init;
end
end
推荐答案
对于这些sif (match == 0)
内容,我无能为力-如果应该是if (match == 0)
,则您无需更改match
,因此可以被带到循环之外.
I can't help you with this sif (match == 0)
stuff -- if it's supposed to be if (match == 0)
you're not changing match
so it could be brought outside the loop.
否则,如何处理?
[min_w, min_w_index] = min(w, [], 3);
r = repmat((1:height)',1,width);
c = repmat(1:width,height,1);
ind = sub2ind(size(w),r(:),c(:),min_w_index(:));
w_mean(ind) = double(fr_bw);
w_sd(ind) = repmat(sd_init,height,width);
(请注意,mean
是内置函数,因此我将您的变量重命名为w_mean
和w_sd
.)
(Please note that mean
is a built-in function so I renamed your variables to w_mean
and w_sd
.)
sub2ind
调用为您提供与下标相对应的线性索引. (直接下标将不起作用; z([a1 a2 a3],[b1 b2 b3],[c1 c2 c3])
引用z
数组中的27个元素,而下标是指定下标的笛卡尔积,而不是您可能期望的z(a1,b1,c1)
和z(a2,b2,c2)
和z(a3,b3,c3)
)
The sub2ind
call gives you linear indices that correspond to subscripts. (Direct subscripts won't work; z([a1 a2 a3],[b1 b2 b3],[c1 c2 c3])
refers to 27 elements in the z
array with subscripts that are the cartesian product of the specified subscripts, rather than z(a1,b1,c1)
and z(a2,b2,c2)
and z(a3,b3,c3)
that you might expect.)
以下是此技术的说明:
>> height = 6; width = 4;
>> w = randi(1000,height,width,2)
w(:,:,1) =
426 599 69 719
313 471 320 969
162 696 531 532
179 700 655 326
423 639 408 106
95 34 820 611
w(:,:,2) =
779 441 638 696
424 528 958 68
91 458 241 255
267 876 677 225
154 519 290 668
282 944 672 845
>> [min_w, min_w_index] = min(w, [], 3);
>> min_w_index
min_w_index =
1 2 1 2
1 1 1 2
2 2 2 2
1 1 1 2
2 2 2 1
1 1 2 1
>> z = zeros(height,width,2);
>> r = repmat((1:height)',1,width);
>> c = repmat(1:width,height,1);
>> ind = sub2ind(size(w),r(:),c(:),min_w_index(:));
>> z(ind) = 1
z(:,:,1) =
1 0 1 0
1 1 1 0
0 0 0 0
1 1 1 0
0 0 0 1
1 1 0 1
z(:,:,2) =
0 1 0 1
0 0 0 1
1 1 1 1
0 0 0 1
1 1 1 0
0 0 1 0
这篇关于MATLAB向量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!