# How to automate dimensional expansion elegantly（broadcasting mechanism）?

1 view (last 30 days)
cui on 2 Aug 2021
Answered: Chunru on 2 Aug 2021
For example, I have a RGB image and for each channel I need to subtract the mean and divide by the standard deviation, where meanRGB = [0.485, 0.456, 0.406]; stdRGB = [0.229, 0.224, 0.225]; How can I write the code in an elegant and concise way?
The common way to write it is：
meanRGB = [0.485, 0.456, 0.406];
stdRGB = [0.229, 0.224, 0.225];
oriImg = imread('peppers.png'); % RGB，[0,255] range
inferenceSize = size(oriImg,[1,2]);
img = rescale(oriImg,0,1);% 转换到[0,1],h*w*c,RGB顺序
% The usual way of writing, the code is slightly more complicated
Rmean = meanRGB(1)*ones(inferenceSize);
Gmean = meanRGB(2)*ones(inferenceSize);
Bmean = meanRGB(3)*ones(inferenceSize);
Rstd = stdRGB(1)*ones(inferenceSize);
Gstd = stdRGB(2)*ones(inferenceSize);
Bstd = stdRGB(3)*ones(inferenceSize);
RGBmean = cat(3,Rmean,Gmean,Bmean);
RGBstd = cat(3,Rstd,Gstd,Bstd);
img = (img-RGBmean)./RGBstd;
And for the same operation, the python writeup is much more elegant for dimensional expansion, with just the following lines.
meanRGB = (0.485, 0.456, 0.406)
stdRGB = (0.229, 0.224, 0.225)
img = (img - meanRGB)/stdRGB # only one line code! automatic broadcasting mechanism

Chunru on 2 Aug 2021
meanRGB = [0.485, 0.456, 0.406];
stdRGB = [0.229, 0.224, 0.225];
oriImg = imread('peppers.png'); % RGB，[0,255] range
img = rescale(oriImg,0,1);% 转换到[0,1],h*w*c,RGB顺序
% change the mean and std into "compatiable" shape for array expansion
meanRGB = reshape(meanRGB, [1,1,3]);
stdRGB = reshape(stdRGB, [1, 1, 3]);
% Array automatic expansion to 1st and 2nd dims
img = (img-meanRGB)./stdRGB;

R2021a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by