计算不同参数值的平均模拟

时间:2017-01-12 21:17:59

标签: matlab matlab-figure

我正在研究类似于以下示例的内容: 我想计算<x(t)>,它是函数x(t)在模拟次数上的平均值。为此,我生成以下代码:

sim=50;% number of simulations 
t=linspace(0,1);% time interval

a_range=[1,2,3];% different values for the parameter a
b_range=[0,0.5,1];% different values for the parameter b
z=zeros(1,sim);
theta=zeros(1,sim);

for nplot=1:3
   a=a_range(nplot);
   b=b_range(nplot);
   average_x=zeros(nplot,sim);
   for i=1:sim
       z(i)=rand(1);% random number for every simulation
       theta(i)=pi*rand(1);% random number for every simulation    
    x=z(i)*t.^2+a*sin(theta(i))+b.*tan(theta(i));% the function

   end
   average_x(nplot,sim)=mean(x);% average over the number of simulations
end

fname=['xsin.mat'];
save(fname)

时间是向量1乘100,x是向量1乘100,average_x是1乘50.我正在寻找的是编写一个脚本来加载文件并绘制不同参数的平均时间a和b。所以我想编写一个代码来生成三个数字,这样在图1中我将绘制平均值

plot(t,average_x)

表示a = 1且b = 0。

然后在图2中,我将再次绘制平均值,但a = 2且b = 0.5,依此类推。问题是时间t的维数和平均值是不一样的。我该如何解决这个问题,并生成三个不同的数字。

1 个答案:

答案 0 :(得分:2)

如果我的意图正确,那就是你要找的:

sim = 50;% number of simulations 
t = linspace(0,1);% time interval

a_range = [1,2,3];% different values for the parameter a
b_range = [0,0.5,1];% different values for the parameter b

% NO NEED TO GENERATE THE RANDOM NUMBERS ONE BY ONE:
theta = pi*rand(sim,1);% random number for every simulation
z = rand(sim,1); % random number for every simulation

% YOU SOULD INITIALIZE ALL YOUR VARIABLES OUTSIDE THE LOOPS:
x = zeros(sim,numel(t)); 
average_x = zeros(3,numel(t));% the mean accross simulations
% for average accros time use:
% average_x = zeros(3,sim);

for nplot=1:3
   a = a_range(nplot);
   b = b_range(nplot);
   for i=1:sim
       x(i,:) = z(i)*t.^2+a*sin(theta(i))+b.*tan(theta(i));% the function
   end
   average_x(nplot,:) = mean(x); % average over the number of simulations
   % average_x(nplot,:) = mean(x,2); % average accross time
end
% save the relevant variables:
save('results.mat','average_x','t')

在另一个文件中,你可以写:

load('results.mat')
for k = 1:size(average_x,1)
    figure(k)
    plot(t,average_x(k,:))
    title(['Parameter set ' num2str(k)])
    xlabel('Time')
    ylabel('mean x')
end

这是一个图中的情节(如果你想平均而不是模拟):

mean sim

顺便说一句,如果你想让你的代码更加紧凑和快速,你可以使用bsxfun进行矢量化。以下是您的代码演示:

% assuming all parameters are defined as above:
zt = bsxfun(@times,z,t.^2); % first part of the function 'z(i)*t.^2'
% second part of the function 'a*sin(theta(i)) + b.*tan(theta(i))':
ab = bsxfun(@times,a_range,sin(theta)) + bsxfun(@times,b_range,tan(theta));
% convert the second part to the right dimensions and size:
ab = repmat(reshape(ab,[],1,3),1,numel(t),1); 
x = bsxfun(@plus,zt,ab); % the function
average_x = squeeze(mean(x)); % take the mean by simulation
plot(t,average_x) % plot it all at once, as in the figure above
xlabel('Time')
ylabel('mean x')