Matlab loops for a function

萝らか妹 提交于 2019-12-13 09:33:52

问题


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...



来源:https://stackoverflow.com/questions/1894978/matlab-loops-for-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!