arrays - 矢量化- Matlab

标签 arrays matlab vectorization

给定一个向量

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)]

但我想知道是否有更优雅(稳健)的解决方案?

最佳答案

针对一般情况使用 difffindcumsum 的一种方法 -

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

相关文章:

javascript - 检查对象数组中的任何键是否包含数组对象数组中的值的最佳方法是什么?

android - 如何检查 Android 中数组中存在的数据?

r - 将 MATLAB 脚本集成到 R Markdown 文档中

r - 具有最大操作的高效双 for 循环

python - 矢量化以实现性能

python - 在多维数组上使用 numpy.where

java - 使用数组时出现 NullPointerException

windows - 在不失去焦点的情况下启动 matlab 命令窗口

c++ - 为 Levenberg-Marquardt 算法构建 Mex 时出错 - 表示存在的目录不存在

python - 在没有 scipy.sparse 的情况下向量化稀疏和