我有一个交替包含 0 和 1 的向量,我想将每个“1”转换为它前面的零的长度。例如,我有 x 并想到达 y:
x = [0 0 1 0 0 0 0 1 0 0 0 1 1 0 0 1]
y = [0 0 2 0 0 0 0 4 0 0 0 3 0 0 0 2]
我非常感谢有关如何实现这一目标的任何建议。
最佳答案
%// Initialize array, y with zeros and of length same as input, x
y = zeros(size(x))
%// Find places/indices where new values would be put
idx = find(x)
%// Calculate new values which would be the differentiated values of indices
%// and subtracted by 1 to account for the number of zeros in between two
%// non-zero values. We need to concatenate the indices array with one zero
%// at the start to account for the starting non-zero value in x
y(idx) = diff([0 idx])-1
关于matlab - 查找 0's separating islands of 1' 的长度并分配它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29106214/