2012-11-09 224 views
3

如何在matlab中编写递归函数,它基本上是一个马尔可夫链! 我试图写它和伪代码新MATLABmatlab中的递归函数

的功能发生是这样的:

P= Probability 
    x= status(0,1) 
    Dij= probability to pick a site 
    P(Status of Site(i) being x at next time step)= Summation[P(Status of Site(i) being x at previous time step)*Dij] 

我已经试过代码,任何人都可以电话我是否其右:

function [t,index]= CopyingInfluenceModel 
%%Define constants 
StatusP1=rand(1,0); 
StatusP0=rand(1,0); 

% Initializing the variables 
t=[]; 
index=[]; 
i=[]; 
%assigining the initial conditions 
t(1)=0; 
%set index no i to 1(initial condition for i=1) 
i=1; 
%% If the probability is zero, terminate while loop 
while p(i)>=0 
%calculate time step for given index no 
t(i+1)= t(i); 
%calculate the status_probability at given time t=(i+1) 
StatusP1(i+1)=StatusP1(i)+sum(StatusP1(i)*Dij); 

%index i increases by 1 to calculate next probability 
i=i+1; 
end 
end 
+0

如果我可能如此大胆(也可能不正确),在我看来,这将更顺利地完成没有递归,因为在生成斐波那契序列的线性解决方案(这是你似乎试图做的) –

+0

不是斐波那契! – happyme

回答

3

首先在matlab中递归的“Hello World”阶乘函数:

function result=f(x) 
if (x<=0) 
    result=1; 
else 
    result=x*f(x-1); 
end 

end 

可以这样调用:

>> f(4) 
ans = 
    24 

不知道太多关于马尔可夫链,我在你的功能是应该做的做一个猜测这里。首先代码:

function yourmainscript 
    % state 1 -> state 1: 50% 
    % state 1 -> state 2: 50% 
    % state 2 -> state 1: 25% 
    % state 2 -> state 2: 75% 
    D=[0.5 0.5; 0.25 0.75]; 
    p0=[1; 0]; 

    % Get probability that the system is in state number 1 at time step number 4 
    % given the transition matrix D and the initial probabilities p0 
    P(1,4,D,p0) 
end 

function result=P(state, t, D, p0) 
if t==0 
    result=p0(state); 
else 
    possible_states=(1:length(D))'; 
    result=D(state,:)*arrayfun(@(x) P(x, t-1, D, p0), possible_states); 
end 
end 

参数D和p0描述系统,只是通过未经修改。只要可访问,使用全局变量或使用函数嵌套功能也适用于它们。

state是一个介于1和你处理的状态总数之间的整数,t是一个表示时间步长的整数。

在t == 0时,我们可以使用状态作为p0的索引来获得概率。 对于t> 0,我把这个总和改写为一个矩阵乘法:

我们需要Dij的行(它是由当前状态给出的D(state,:))并将它乘以所有概率的向量在最后时间步长可能的状态。

线

possible_states=(1:length(D))'; 

是含有1,2,3,列向量...,最后的状态,并且需要在下一行。Arrayfun调用一个函数(第一个参数)作为数组的每个元素(第二个参数)并将结果填充到一个向量中。第一个参数是定义下面的函数的简写nction:

function result=wrapperfunction(x) 
    % Assume t, D and p0 are in scope and the function P is known 
    result=P(x, t-1, D, p0); 
end 

请注意,MATLAB是大小写敏感的,所以如果你定义一个函数“马氏”,那么MATLAB还没有现在关于“马氏”。

编辑:对不起,我在撰写答案时更新了代码,因此它可能适用于更新的版本,也可能不适用。