Reputation: 91
I have the variables
X = 1x20 vector of doubles
i = 0:M
j = 0:M
And the equation
sum n=1 to length(X) : (X(n)^(i+j))
Is there a way to obtain an MxM matrix (through the indices i,j) while summing out n in each cell? I tried this with symsum but it doesn't allow indexing with n.
Any help is appreciated!
Upvotes: 2
Views: 44
Reputation: 15867
By reshaping X
to a vector of size [1 x 1 x 20]
and using implicit expansion a 3D [M+1 x M+1 x 20]
array is created then by summing along the third dimension the result can be obtained.
X = rand(1,20);
M = 30;
ii = 0:M;
jj = (0:M).';
Y = reshape(X,1,1,[]);
result = sum(Y.^(ii+jj), 3);
However as the expression Y.^(ii+jj)
creates a 3D [M+1 x M+1 x 20]
array it may need a large amount of memory that leads to decreased performance.
We know that x^(i+j)
can be written as x^i * x^j
So the expression can be written as:
result = sum(Y.^ii .* Y.^jj,3);
It has the same memory consumption as the previous method. But when we reach an expression that contains sum of products we should think about converting it to very fast matrix multiplication :
Z = X .^ jj; % A [M+1 x 20] matrix is created(implicit expansion)
result = Z * Z.' % multiply Z by its transpose
So the same result is obtained without the complexity of the other solutions.
Upvotes: 3