Symsum iteration over non-symbolic array problem

1 view (last 30 days)
Hello,
I want to generate the sum of a series of log functions l(x) that have two parameters (n, g).
n = 5;
g = 0:4; %example array
syms l(x) k
l(x) = g*log(x)+(n-g)*log(1-x);
Ls(x) = symsum(l,k,1,n);
One parameter (g) is always an array of varying size. l(x) generates a function for each element of g as expected. I would like to get the sum equation for all l(x), in this case:
Ls(x) = 15*log(1-x)+10*log(x)
However for symsum, Ls produces a k-times summation of l(x) for each element of g separately:
Ls(x) =
[ 25*log(1 - x), 20*log(1 - x) + 5*log(x), 15*log(1 - x) + 10*log(x), 10*log(1 - x) + 15*log(x), 5*log(1 - x) + 20*log(x)]
I was under the impression I could use symbolic equations and symsum here because I wanted the final equation.
Do you have any suggestion on how to approach this since I can't use k to index?

Answers (1)

Shishir Reddy
Shishir Reddy on 26 Dec 2024
Hi Stefan
As per my understanding, you would like to generate the sum of a series of log functions l(x). To achieve the desired resut, the expressions generated for each element in the array g need to be summed manually without using symsum. Here's how it can be done in MATLAB.
syms x
n = 5;
g = 0:4;
total_sum = 0;
% Each element of g is looped through, and the expressions are summed
for i = 1:length(g)
l = g(i)*log(x) + (n-g(i))*log(1-x);
total_sum = total_sum + l;
end
disp(total_sum);
In MATLAB, vectorization can often lead to more efficient computations by eliminating explicit loops. In this case, the vectorization can be performed as follows.
l_vector = g .* log(x) + (n - g) .* log(1 - x);
total_sum = sum(l_vector);
disp(total_sum);
For more information regarding vectoriztion, kindly refer the following documentation -
I hope this resolves the issue.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!