如何在一个循环中求和一个函数的输出?

时间:2019-05-29 20:00:04

标签: matlab while-loop sum

我试图简单地将迭代1到1000的所有“ LengthofRoute”数字相加,这样我就可以计算出1000个迭代中的平均LengthofRoute。我怎样才能做到这一点?我已经搜寻了互联网,找不到正确的程序。 Dijsktra1执行并返回通常小于4的整数。

J=0;
f = 0;
nf = 0;
while J<1000
    LengthofRoute = [];
    B = RandomMatrix(0,1,10,10);
    J=J+1;
    [LengthofRoute, RouteTaken] =Dijkstra1(B, 10, 1);

    if LengthofRoute > 0
        f = f + 1;
        % number of feasible occurrences
    else 
        nf = nf + 1;
        % number of nonfeasible occurrences
    end
    LengthofRoute = LengthofRoute + LengthofRoute
end

1 个答案:

答案 0 :(得分:1)

您应该只使用一个单独的累加器来累加LengthofRoute

假设LengthofRouteSum正在累积总和。

  1. 在循环之前初始化LengthofRouteSumLengthofRouteSum = 0;
  2. 在循环的底部累积LengthofRouteLengthofRouteSum = LengthofRouteSum + LengthofRoute;

以下代码应完成工作:

J=0;
f = 0;
nf = 0;
LengthofRouteSum = 0;
while J<1000

    B = RandomMatrix(0,1,10,10);
    J=J+1;    
    [LengthofRoute, RouteTaken] =Dijkstra1(B, 10, 1);

    if LengthofRoute > 0
        f = f + 1;
        % number of feasible occurrences
    else 
        nf = nf + 1;
        % number of nonfeasible occurrences
    end
    LengthofRouteSum = LengthofRouteSum + LengthofRoute;
end