precision while using anonymous function

1 view (last 30 days)
themaze
themaze on 29 Oct 2017
Answered: Walter Roberson on 29 Oct 2017
I have an anonymous function and the same operation using matrix manipulations. I am getting different results. what could be the issue
clc
X = rand(2000, 2000);
Npts = size(X,1);
alpha = 1;
d = 3;
kfunc = @(alpha, d, xi, xj) (alpha*(xi* xj') ).^d;
for j=1:Npts
K1(:,j) = kfunc( alpha, d, X, X(j,:));
end
K2 = ( alpha*(X*X')).^ d;
diff = abs(K2-K1);
sum(sum(diff))

Answers (1)

Walter Roberson
Walter Roberson on 29 Oct 2017
The difficulty is not that you used anonymous functions. The difficulty is that you did the calculation in a different way.
There are patterns of operations that MATLAB can recognize, and when it finds them, it passes the data on to a high performance multi-threaded library to do the calculations. That library will divide up the work and use all available cores, and then combine the results. The exact order that it splits up the calculations can depend upon the sizes and orientation involved.
Floating point calculations round off and the round-off depends upon the order of the calculations. http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F, so the fragments sliced different ways will have different round-offs, and so the recombinations will come out differently.

Categories

Find more on Graphics Object Programming 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!