Is there an advantage to using linear algebra as opposed to operations with elements by elements?

For example, in the event of a regression problem, you can sum the square of the difference between two vectors containing data. I can do this in several ways, if we have:

    x = [3 4 5 6];
    y = [2 4 6 3];

I can write:

    sum((x-y).^2)

or

    (x-y)*(x-y)'

Both of them return the same value. 11. This is just one example of a calculation that can be done in any case, but I wonder if there is a reason for the choice one way or another, and also if there are different types of tasks in which it would be advisable to choose one path over another.

+4
source share
2 answers

The first variation can be expanded to process several sets of input data at once:

x = [3 4 5 6;1 2 3 4];
y = [2 4 6 3;4 3 2 1];
sum((x-y).^2,2)

. (, sum) , dim, , . , . , ,

yourfun(x,y,dim)=sum((x-y).^2,dim)
+1

, sum(x.^2) x*x' 1xN Matlab?

, . .

x = rand(1, 1e6);

tic;
for i = 1:1e2
    x * x';
end;
toc;

tic;
for i = 1:1e2
    sum(x.^2);
end;
toc;

2012b:

Elapsed time is 0.057315 seconds.
Elapsed time is 0.289310 seconds.
0

Source: https://habr.com/ru/post/1544972/


All Articles