Matlab loops for a function

2019-09-20 06:07发布

问题:

I am trying to make a loop to redo a Matlab function 1000 times. Here's the program

d = unifrnd (0,10,[10,1]);
c = d.^(-2);
a = round(unifrnd(0,1,[1,10]);
e = a*c
btotal = e+1
SIR = 1/btotal

What I want is to iterate this function 1000 times, each time the value of SIR will vary due to the random number generated. For every iteration, I want the value of SIR to be added together (summed up), and in the end of the 1000th iteration, find the average SIR(mean).

Thanks for the help

回答1:

The code below implements what you described:

genSIR.m

function SIR = genSIR()
    d = unifrnd (0,10,[10,1]);
    c = d.^(-2);
    a = round(unifrnd(0,1,[1,10]));
    e = a*c;
    btotal = e+1;
    SIR = 1/btotal;
end

main program

N = 1000;
SIR = zeros(N,1);
for i=1:N
    SIR(i) = genSIR();
end
s = sum(SIR)
m = mean(SIR)

although your function could be simplified...