MATLAB vectorize

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
0
source share
2 answers

I cannot help you with this material sif (match == 0)- if it should be if (match == 0), you do not change matchit so that it can be taken outside the cycle.

Otherwise, how about this:

[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);

(Note that this meanis a built-in function, so I renamed your variables to w_meanand w_sd.)

sub2ind , . ( ; z([a1 a2 a3],[b1 b2 b3],[c1 c2 c3]) 27 z , , z(a1,b1,c1) z(a2,b2,c2) z(a3,b3,c3), .)

:

>> 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
+1

:

  • if, sif?

  • , w, fr_bw sd_init. .

  • , mean. mean , , .

  • , , double , , , . double; . ( , fr_bw - , , dbl_fr_bw = double(fr_bw);.

, ,

[min_w, min_w_index] = min(w, [], 3)

mean_values(:, :, min_w_index) = double(fr_bw)

>

, , sd_init /.

0

All Articles