matlab - 查找 0's separating islands of 1' 的长度并分配它们

标签 matlab count zero

我有一个交替包含 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]

我非常感谢有关如何实现这一目标的任何建议。

最佳答案

一种方法 find & diff -

%// 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/

相关文章:

sql - 以最优化的方式从sql server表中获取记录数

r - 如何使用 R 编程按列值分组

java - 将字符串解析为带前导零的长

powershell - 0 不是 PowerShell 中的 [int]?

matlab - 在 matlab 中呈现随机游走者的运动

matlab - 相当于 `evalin` 不需要输出参数(内部)

matlab - 在matlab中访问单元格数组的第n列

MySQL 计算联合表中的行数

java - 前面有零的整数是什么意思,我该如何打印它?

image - 在 MATLAB 中将图像绘制为轴标签