在matlab脚本中循环

时间:2014-02-21 16:27:01

标签: matlab loops

我正在使用matlab作为我最后一年项目的一部分。我正在解决几何系列,例如x ^ j的总和,从j = 0到n-1。到目前为止,我有以下代码:

$Variable dictionary
%N Number of terms to sum
%alpha Sum of series
%x Vector of constants 
%n Loop counter

N = input('Enter the number of terms to sum: ');
alpha = 0;
x = [0.9 0.99 0.999 0.9999 0.99999 0.999999];
for n = 0:N-1
alpha = alpha + (x.^(n));
end
format long
alpha

当我运行这个脚本时,它允许我在脚本中将x的值作为向量输入,但要求用户输入n的值。无论如何,我可以修改我的代码,以便我可以把自己的n?并使其超过一个n?

的值

谢谢

3 个答案:

答案 0 :(得分:2)

也许这就是你想要的(不需要循环):

x = [0.9 0.99 0.999 0.9999 0.99999 0.999999];
n = [1 2 5];

alphas = sum(bsxfun(@power, x(:), n(:).')); %'// one result for each value of n

答案 1 :(得分:1)

修改这部分代码:

for n = 1: length(N)
alpha = alpha + (x.^(N(n)));
end

并将N作为向量传递[10 100 1000]

答案 2 :(得分:0)

这是一个解决方案:

x = [0.9 0.99 0.999 0.9999 0.99999 0.999999];
nlist = [10,100,1000];
for elm = nlist
    alpha = alpha + (x.^(elm));
end