Correct use of arrayfun
20 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
采纳的回答
Matt J
2018-1-29
编辑:Matt J
2018-1-29
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 个评论
Matt J
2018-1-30
but it is faster also.
Faster, you mean, than implicit scalar expansion? Very strange!
Jan
2018-1-30
编辑:Jan
2018-1-30
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!