MATLAB: How to speed up iterating through two large nested for loops and subtracting one array from another

arrayMATLABvectorization

I have tried vectorization with bsxfun(), but could not get the code working. I also tried meshgrid() but it requires too much memory. The data line isn't code and is just the dimensions for clarity.
data = 25x1536x2048
[Nt, Nv, Nh] = size(data);
MUvh = reshape(mean(data,1), [Nv Nh]);
for ii = 1:Nv
for jj = 1:Nh
data(:,ii,jj) = data(:,ii,jj) - MUvh(ii,jj);
end
end

Best Answer

If I understand correctly what you want to do, that is to subtract the mean of ‘data’ across dimension 1 from ‘data’, this will work:
data = 25x1536x2048
MUvh = mean(data,1);
result = bsxfun(@minus, data, MUvh);
It produced the correct result with some test data I used.