我有一个随机散布1s
的矩阵:-1s
0s
%// 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
我想计算nonzero
元素在一列中重复的次数,以产生如下内容:
基本思想是(由@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
实现此目的最干净的方法是什么?