2

I'd like to optimise the following code, which is just a matrix multiplication - I'm sure this can be done without the use of loops - but I can't quite seem to get it right.

k = [ 76    150    29; ...
     -44   -85    128;  ...
     128   -108   -21];

for i = 1:size(rgb,1)
  for j = 1:size(rgb,2)
    triplet(1:3) = rgb(i,j,:);
    yuv(i,j,:)   = single(triplet) * single(k');
    yuv(i,j,:)   = fix(yuv(i,j,:) ./ 256);
  end
end

Any thoughts or suggestions?

By the way for those with an image processing background, you'll realise the above code is just simply an RGB to YUV conversion - and you might ask why don't I use the builtin rgb2ycbcr function - However on this occasion I want to use the 8bit conversion coefficients as outlined above.

user2469775
  • 447
  • 4
  • 11
trican
  • 1,157
  • 4
  • 15
  • 24

1 Answers1

6

You can reshape

rgbR = reshape( rgb, [], 3 );
yuvR = single(rgbR) * single( k' );
yuv = reshape( fix( yuvR./ 256 ), size(rgb,1), size(rgb,2), [] );

PS,
It is best not to use i and j as variable names in Matlab.

Community
  • 1
  • 1
user2469775
  • 447
  • 4
  • 11
  • It's perfectly fine to use `i` and `j` as variable names and there was nothing wrong with @trican's use. That is not at all what that the linked "question" and answers state. – horchler Jun 10 '13 at 20:43
  • @horchler I am **not** claiming using `i` is wrong of that trican's code is in any way not good. I just think (and the linked question as well) that it is a good practice not to use `i` as a variable name in Matlab. – user2469775 Jun 11 '13 at 19:11