I was wondering if anyone could help me vectorize this piece of code.
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
I can't help you with this
sif (match == 0)
stuff -- if it's supposed to beif (match == 0)
you're not changingmatch
so it could be brought outside the loop.Otherwise, how about this:
(Please note that
mean
is a built-in function so I renamed your variables tow_mean
andw_sd
.)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 thez
array with subscripts that are the cartesian product of the specified subscripts, rather thanz(a1,b1,c1)
andz(a2,b2,c2)
andz(a3,b3,c3)
that you might expect.)Here's an illustration of this technique:
A few comments on your code:
Did you mean
if
rather thansif
?The code isn't replicable at the moment, since you haven't provided examples of the variables
w
,fr_bw
andsd_init
. This makes it tricky to give an exact answer.It looks like you are assigning things to a variable named
mean
. This will shadow themean
function, and probably cause you grief.I'm just guessing, but I don't think
double
does what you think it does. You don't need to convert individual elements of a numeric matrix to typedouble
; they are already the correct type. (On the other hand, iffr_bw
is a different type, say integers, then you should create a new variabledbl_fr_bw = double(fr_bw);
before the loops.You might need to adjust the dimension over which you calculate the minimums, but the first line of the loop can be replaced with
The second line withNot sure about the third line, since I don't know what
sd_init
is/does.