gpt4 book ai didi

arrays - 矢量化- Matlab

转载 作者:行者123 更新时间:2023-12-02 06:57:05 24 4
gpt4 key购买 nike

给定一个向量

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/

24 4 0
文章推荐: c - 单独使用时难以理解 c 指针(第 2 部分)
文章推荐: perl - 仅从 fasta 文件中提取第一个序列
文章推荐: haskell - 过滤器 foo [2..n] 的内存使用! 0
文章推荐: php - 将 元素包装在
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com