Try this in MATLAB:
z = sum(X.*(A*X));
This gives results equivalent to the Federico suggestion using the DOT function, but should work a little faster. This is because the DOT function internally calculates the result in the same way as I did above using SUM . However, the DOT also has additional checks of input arguments and additional calculations for cases when you are dealing with complex numbers that the extra overhead probably does not want or need.
A note on computational efficiency:
Despite the fact that the time difference is small between how quickly these two methods work, if you intend to perform the operation many times, it will begin to add up. To check the relative speeds, I created two 100-by-100 matrices of random values ββand timed two methods for many runs to get the average execution time:
METHOD AVERAGE EXECUTION TIME -------------------------------------------- Z = sum(X.*Y); 0.0002595 sec Z = dot(X,Y); 0.0003627 sec
Using SUM instead of DOT therefore reduces the execution time of this operation by about 28% for matrices with about 10,000 elements. The larger the matrix, the negligible difference between the two methods will be.
To summarize, if this calculation presents a significant bottleneck in how fast your code works, I would go with a solution using SUM . Otherwise, any decision should be in order.
source share