给定一个向量
X = [1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3]
我想生成一个这样的向量
Y = [1 2 3 4 5 1 2 3 4 5 6 1 2 3 4 5]
到目前为止我得到的是
idx = find(diff(X))
Y = [1:idx(1) 1:idx(2)-idx(1) 1:length(X)-idx(2)]
但我想知道是否有更优雅(稳健)的解决方案?
最佳答案
针对一般情况使用 diff
、find
和 cumsum
的一种方法 -
%// Initialize array of 1s with the same size as input array and an
%// intention of using cumsum on it after placing "appropriate" values
%// at "strategic" places for getting the final output.
out = ones(size(X))
%// Find starting indices of each "group", except the first group, and
%// by group here we mean run of identical numbers.
idx = find(diff(X))+1
%// Place differentiated and subtracted values of indices at starting locations
out(idx) = 1-diff([1 idx])
%// Perform cumulative summation for the final output
Y = cumsum(out)
sample 运行-
X =
1 1 1 1 2 2 3 3 3 3 3 4 4 5
Y =
1 2 3 4 1 2 1 2 3 4 5 1 2 1
只是为了好玩,但是习惯bsxfun
的替代解决方案-
%// Logical mask with each column of ones for presence of each group elements
mask = bsxfun(@eq,X(:),unique(X(:).')) %//'
%// Cumulative summation along columns and use masked values for final output
vals = cumsum(mask,1)
Y = vals(mask)
关于arrays - 矢量化- Matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243376/