Trying to calculate partial sums of e^10 in Matlab?

后端 未结 2 1013
情歌与酒
情歌与酒 2021-01-25 01:54

I\'ve written the function:

function [sum] = func(a,b)
sum = 0;
for i = 0:b
    sum = sum + ((a.^i)/(factorial(i)));
end

In the console, the co

2条回答
  •  梦毁少年i
    2021-01-25 02:43

    Well, if you don't index sum with i, you return a single value.

    Try instead:

    function [sum] = func(a,b)
    
    % Pre-allocate sum at the right size
    sum = NaN(1,b+1);
    
    % Compute
    for i = 0:b
        sum(i+1) = sum(i+1) + ((a.^i)/(factorial(i)));
    end
    

    Best,

提交回复
热议问题