我有一个由随机分布的0s
组成的1s
和-1s
的矩阵:
%// create matrix of 1s and -1s
hypwayt = randn(10,5);
hypwayt(hypwayt > 0) = 1;
hypwayt(hypwayt < 0) = -1;
%// create numz random indices at which to insert 0s (pairs of indices may
%// repeat, so final number of inserted zeros may be < numz)
numz = 15;
a = 1;
b = 10;
r = round((b-a).*rand(numz,1) + a);
s = round((5-1).*rand(numz,1) + a);
for nx = 1:numz
hypwayt(r(nx),s(nx)) = 0
end
输入:
hypwayt =
-1 1 1 1 1
1 -1 1 1 1
1 -1 1 0 0
-1 1 0 -1 1
1 -1 0 0 0
-1 1 -1 -1 -1
1 1 0 1 -1
0 1 -1 1 -1
-1 0 1 1 0
1 -1 0 -1 -1
我想要统计一列中
非零
元素重复出现的次数,生成如下所示的内容:
基本思路是(由@rayryeng提供)对于每一列,独立统计每次遇到一个唯一的数字时,开始递增累积计数器,并且每次遇到与前一个相同的数字都递增。一旦遇到新数字,计数器就会被重置为1,除了当遇到0时,此时计数器为0。
期望输出:
hypwayt_runs =
1 1 1 1 1
1 1 2 2 2
2 2 3 0 0
1 1 0 1 1
1 1 0 0 0
1 1 1 1 1
1 2 0 1 2
0 3 1 2 3
1 0 1 3 0
1 1 0 1 1
什么是最干净的方法来完成这个任务?
hypwayt_runs
是如何计算的?我没有看出其中的规律(遗憾)。 - rayryeng