Correct use of arrayfun

조회 수: 3 (최근 30일)
GEORGIOS BEKAS
GEORGIOS BEKAS 2018년 1월 29일
편집: Jan 2018년 1월 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)

채택된 답변

Matt J
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
Matt J 2018년 1월 30일
but it is faster also.
Faster, you mean, than implicit scalar expansion? Very strange!
Jan
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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by