我如何在 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
最佳答案
首先是 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,...,last state 的列向量,需要在下一行中使用。 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”。
编辑:抱歉,在我撰写此答案时您已经更新了代码,因此它可能适用于也可能不适用于更新版本。
关于matlab - matlab中的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13311289/