Matlab 计算级数之和

Matlab 计算级数之和,matlab,for-loop,iteration,vectorization,series,Matlab,For Loop,Iteration,Vectorization,Series,我需要计算这个级数的和 我需要这样的输出: If n = 3; x = function_name(n) 我需要得到x=11。 If n = 5; x = function_name(n) 我需要得到x=45 我相信我需要一个for循环来迭代;但是我发现很难迭代增量值本身。我想你想要的是数字的差异: d = 2; n = 5; s = d:d:d*(n-1) cs = cumsum( [1 s] ) scs = sum(cs) %// or as anonymous funct

我需要计算这个级数的和

我需要这样的输出:

If n = 3;

x = function_name(n)
我需要得到x=11。

If n = 5;

x = function_name(n)
我需要得到
x=45

我相信我需要一个for循环来迭代;但是我发现很难迭代增量值本身。

我想你想要的是数字的差异:

d = 2;
n = 5;

s  =  d:d:d*(n-1)
cs  = cumsum( [1 s] )
scs = sum(cs)

%// or as anonymous function

scsh = @(n,d) sum( cumsum( [1 d:d:d*(n-1)] ) )


不需要循环

我只需要图表第2列中的数字之和,即n=5的级数;我需要1+3+7+13+21=45;Matlab函数只能接受一个输入;也就是n。如果我提供n=3的输入,那么Matlab需要取11作为输出;我需要在函数内部开发序列,然后生成sum。图中的最后一列(序列中的数字之间的差异)仅用于编码目的,非常感谢;我认为它有效;但是,有没有一种解决方案可以提供给使用for-loop的用户,也可以使用while.loop。我也想到了另一种方法。这也很有效;无论如何,感谢你们两位,特别是@netizen
inc=2;
sum=1;
next=1;

n=input('what is n?\n');

for i=2:n
    next=next+inc;
    sum=sum+next;
    inc=inc+2;
end

disp('sum is ');
disp(sum);
inc=2;
sum=1;
next=1;

n=input('what is n?\n');

for i=2:n
    next=next+inc;
    sum=sum+next;
    inc=inc+2;
end

disp('sum is ');
disp(sum);
function Total = abc(n)

nth_term=1;
Total = 1 ;   


    for  d = 2:2:(2*(n-1))
         nth_term = nth_term + d;       
         Total =Total + nth_term;    

    end

end