Correct use of arrayfun

21 vues (au cours des 30 derniers jours)
GEORGIOS BEKAS
GEORGIOS BEKAS le 29 Jan 2018
Modifié(e) : Jan le 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)

Réponse acceptée

Matt J
Matt J le 29 Jan 2018
Modifié(e) : Matt J le 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) )
  3 commentaires
Matt J
Matt J le 30 Jan 2018
but it is faster also.
Faster, you mean, than implicit scalar expansion? Very strange!
Jan
Jan le 30 Jan 2018
Modifié(e) : Jan le 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by