How to write sum over expressions in MATLAB if some elements are required to be skipped?
13 次查看(过去 30 天)
显示 更早的评论
Hi everyone I wanted to know if there is an easy way to generate MATLAB codes from the complicated symbolic mathematical expressions as shown in the figure. Here, consider that i,j,k runs from 1 to N=10.
I wanted to use that expression further, say solve for some variable as below:
myfun1 = @(x,lambda1) (2*x+lambda1-2);
Any help or suggestion on this aspect will be highly appreciated.
Thanks.
0 个评论
采纳的回答
Walter Roberson
2018-6-16
No, symsum has no possibility of excluding a particular value from the indices.
You can take the symsum and subtract off the value when the indices are those unwanted ones.
However, symsum() is not really the right tool to use when you have a known list of indices (in this case, 1 to 10), as symsum() is intended for finding theoretical formulae, such as converting the taylor expansion of exp(x) back into exp(x) . When you have indexing of elements to do, then symsum() can never be used, as it is not possible to index an array at symbolic locations.
For fixed sets of indices, you should be calculating the values individually, and adding them together. You can typically do that in a vectorized fashion. For example, instead of
syms x
symsum( x*(x+1), x, 1, 20 )
you would
sum((1:20).*(2:21))
or
sum( arrayfun(@(x) x.*(x+1), 1:20 ) )
If you used that last form you could exclude values, such as
sum( arrayfun(@(x) x.*(x+1), setdiff(1:20, 7) ) )
to skip the 7*8 term
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!