我有一个序列x = [12,14,6,15,15,15,15,6,8,8,18,18,14,14]所以我想制作转移概率矩阵。通过等式计算的转移概率矩阵,即概率=(对的数量x(t),后跟x(t + 1))/(对的数量x(t),后跟任何状态)。矩阵应该如下所示
6 8 12 14 15 18
6 0 1/2 0 0 1/2 0
8 0 1/2 0 0 0 1/2
12 0 0 0 1 0 0
14 1/2 0 0 1/2 0 0
15 1/4 0 0 0 3/4 0
18 0 0 0 0 1/2 1/2
按照我可以做的代码
m = max(x);
n = numel(x);
y = zeros(m,1);
p = zeros(m,m);
for k=1:n-1
y(x(k)) = y(x(k)) + 1;
p(x(k),x(k+1)) = p(x(k),x(k+1)) + 1;
end
p = bsxfun(@rdivide,p,y); p(isnan(p)) = 0;
但是这个代码矩阵形式的顺序最大状态按顺序存在,即矩阵变为18 * 18,并且出现更多的零位。我希望我发布的矩阵如何做到这一点。
答案 0 :(得分:1)
第1步 - 组织数据并生成空转换表
x= [12,14,6,15,15,15,15,6,8,8,18,18,14,14]
xind = zeros(1,length(x));
u = unique(x) % find unique elements and sort
for ii = 1:length(u)
xmask = x==u(ii); % locate all elements of a single value
xind = xind+ii*xmask; % number them in the order listed in u
end
输出标记为马尔可夫链(元素是标签而不是有意义的值)
>> u
u =
6 8 12 14 15 18
>> xind
xind =
3 4 1 5 5 5 5 1 2 2 6 6 4 4
第2步 - 构建"从 - 到"每一跳的表格
>> T = [xind(1:end-1);xind(2:end)]
T =
3 4 1 5 5 5 5 1 2 2 6 6 4
4 1 5 5 5 5 1 2 2 6 6 4 4
每列都是过渡。第一行是"来自"标签,第二行是"到"标签。
第3步 - 计算频率并创建转换表
p = zeros(length(u));
for ii = 1:size(T,2)
px = T(1,ii); % from label
py = T(2,ii); % to label
p(px,py) = p(px,py)+1;
end
输出是聚合频率表。每个元素都是一跳的计数。行号是"来自"和列号是"到"。
>> p
p =
0 1 0 0 1 0
0 1 0 0 0 1
0 0 0 2 0 0
2 0 0 1 0 0
1 0 0 0 3 0
0 0 0 1 0 1
例如,3
表示从第5个标签到第5个标签的3个转换(实际值为15
到15
)
步骤4 - 规范化行向量以获得概率表
>> p./repmat(sum(p,2),1,length(u))
ans =
0 0.5000 0 0 0.5000 0
0 0.5000 0 0 0 0.5000
0 0 0 1.0000 0 0
0.5000 0 0 0.5000 0 0
0.2500 0 0 0 0.7500 0
0 0 0 0.5000 0 0.5000
替代循环版
for ii = 1:size(p,1)
count = sum(p(ii,:));
p(ii,:) = p(ii,:)/count;
end
答案 1 :(得分:1)
x=[12,14,6,15,15,15,15,6,8,8,18,18,14,14]; %discretized driving cycle
n=numel(x);%total no of data points in driving cycle
j=0;
z=unique(x); % unique data points in the driving cycle and also in arranged form
m=numel(z); % total number of unique data points
N=zeros(m); % square matrix for counting all unique data points
for k=1:1:m; % using loop cycle for unique data points all combinations; for this k is used
for l=1:1:m;
for i=1:1:n-1;
j=i+1;
if x(i)== z(k) & x(j)==z(l);
N(k,l) = N(k,l)+1;
end
i=i+1;
end
l=l+1;
end
k=k+1;
end
N
s=sum(N,2);
Tpm= N./s %transition probability matrix
答案 2 :(得分:-1)
%%Sample matrix
p=magic(8)
%%Fill rows and cols 3,5 with 0's
p([3 5],:)=0
p(:,[3 5])=0
%%The code
lb=[]
for k = [length(p):-1:1]
if any(p(k,:)) | any(p(:,k))
lb=[ [k],lb ]
else
p(k,:)=[]
p(:,k)=[]
end
end
lb
保留原始索引