# Correct use of arrayfun

10 views (last 30 days)
GEORGIOS BEKAS on 29 Jan 2018
Edited: Jan on 30 Jan 2018
Suppose that I have a matrix a, and I want to do an operation on it, e.g. subtracting the mean of its columns from each element of the matrix. How can i do that by using the command arrayfun?
a = [ 3 6 ; 6 5 ]
arrayfun(@(x) a(i,j)-mean(a(i,:)),a,'UniformOutput',false)

Matt J on 29 Jan 2018
Edited: Matt J on 29 Jan 2018
Well first of all, arrayfun should be a last resort. There are much more optimal ways of doing the mean subtraction you describe as well as many other operations like it. In R2016b or higher,
a-mean(a,1),
else if older than R2016b,
bsxfun(@minus, a, mean(a,1))
But, if you really must use arrayfun, it can be done, for example, as follows
cell2mat( arrayfun(@(i) a(:,i)-mean(a(:,i)), 1:size(a,2), 'uni',0) )
Jan on 30 Jan 2018
Edited: Jan on 30 Jan 2018
I test the speed under R2016b, in which the implicit expansion was still new. Maybe this is the cause for my observation, that it is sometimes slower than an explicit bsxfun. The effects are not consistent, see:
function AutoExpandTest
X = rand(1000, 1000);
n = size(X, 1);
tic
dx = zeros(n, n);
for j = 1:n
dx(j+1:n, j) = sqrt(sum(bsxfun(@minus, X(:, j+1:n), X(:, j)) .^ 2, 1));
dx(j, j+1:n) = dx(j+1:n, j);
end
toc
tic
dx = zeros(n, n);
for j = 1:n
dx(j+1:n, j) = sqrt(sum((X(:, j+1:n) - X(:, j)) .^ 2, 1));
dx(j, j+1:n) = dx(j+1:n, j);
end
toc
tic
for k = 1:1000
Y = bsxfun(@minus, X, mean(X, 2));
end
toc
tic
for k = 1:1000
Y = X - mean(X, 2);
end
toc
end
Under R2016b/Win7:
Elapsed time is 7.603560 seconds. BSXFUN
Elapsed time is 10.218603 seconds. Auto Expand
Elapsed time is 9.134871 seconds. BSXFUN
Elapsed time is 6.894594 seconds. Auto Expand
This is interesting, because in the first example the subtraction is a small part of the computation only and the summation and square root should damp the effects.

### Categories

Find more on Logical in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!