matlab中的递归函数

时间:2012-11-09 15:48:56

标签: matlab recursion

如何在matlab中编写递归函数,它基本上是马尔可夫链! 我尝试为它编写一个伪代码,并为 MATLAB 编写新代码:

这个功能是这样的:

   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

1 个答案:

答案 0 :(得分: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,我们可以使用state作为p0的索引来获得概率。 对于t> 0,我将总和重写为矩阵乘法:

我们需要Dij行(由当前状态给出的D(state,:),并将其与最后一步所有可能状态的概率向量相乘。

该行

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

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

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区分大小写,所以如果你定义一个函数“Markov”,那么matlab现在仍然没有关于“markov”。

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