创建基于另一个向量的重复值上升的向量(MATLAB)

Pyj*_*nja 3 matlab vector repeat

这是一个相对简单的.假设我有以下向量('V1'):

1
1
1
2
2
2
2
3
3
4
4
4
4
5
5
5
Run Code Online (Sandbox Code Playgroud)

我想创建第二个向量V2,它从1开始,并在V1的每次迭代中增加,但随后重置为V1的新值.例如:

1
2
3
1
2
3
4
1
2
1
2
3
4
1
2
3
Run Code Online (Sandbox Code Playgroud)

V1中可能存在单个迭代值,或者多达6个.

解决方案可能会使用for循环,但我想有一个更简单的形式而不需要循环('repmat'浮现在脑海中).

Nic*_*son 6

另一个没有循环的建议.

首先计算重复值的数量

a=histc(v1,unique(v1));
Run Code Online (Sandbox Code Playgroud)

构造计数数组

b = ones(1,sum(a));
Run Code Online (Sandbox Code Playgroud)

现在反击累计和的适当位置:

a = a(1:end-1);
b(cumsum(a)+1) = b(cumsum(a)+1) - a;
Run Code Online (Sandbox Code Playgroud)

最后拿累计金额

cumsum(b)
Run Code Online (Sandbox Code Playgroud)

总共

v1 = [1,1,1,1,2,2,3,3,3,3,3,4];
a=histcounts(v1,[unique(v1),inf]);
b = ones(1,sum(a));
a = a(1:end-1);
b(cumsum(a)+1) = b(cumsum(a)+1) - a;
disp(cumsum(b))
Run Code Online (Sandbox Code Playgroud)

TIMEITs:

在随机排序的输入上运行V1 = sort(randi(100,1e6,1));我在Matlab 2017a中获得以下时间.

  • 格诺维奇的第一个建议是:2.852872e-02
  • 格诺维奇的第二个建议是:2.909344e-02
  • AVK的建议:3.935982e-01
  • RadioJava的建议:2.441206e-02
  • 尼基的建议:9.153147e-03

代码:

function [] = SO()
V1 = sort(randi(100,1e6,1));

t1 = timeit(@() gnovice1(V1)); fprintf("* Gnovic's first suggestion: %d\n",t1);
t2 = timeit(@() gnovice2(V1)); fprintf("* Gnovic's second suggestion: %d\n",t2);
t3 = timeit(@() AVK(V1)); fprintf("* AVK's suggestion: %d\n",t3);
t4 = timeit(@() RadioJava(V1)); fprintf("* RadioJava's suggestion: %d\n",t4);
t5 = timeit(@() Nicky(V1)); fprintf("* Nicky's suggestion: %d\n",t5);


function []=gnovice1(V1)
V2 = accumarray(V1, 1, [], @(x) {1:numel(x)});
V2 = [V2{:}].';

function []=gnovice2(V1)
V2 = ones(size(V1));
V2([find(diff(V1))+1; end]) = 1-accumarray(V1, 1);
V2 = cumsum(V2(1:end-1));

function []=AVK(v)
a= v;
for i=unique(v)'
    a(v==i)= 1:length(a(v==i));
end

function []=RadioJava(vec)
vec = vec(:).';
zero_separated=[1,vec(1:end-1)==vec(2:end)];
c=cumsum(zero_separated);
zeros_ind = ~zero_separated;
d = diff([1 c(zeros_ind)]);
zero_separated(zeros_ind) = -d;
output=cumsum(zero_separated);

function []=Nicky(v1)
v1 = v1(:).';
a=histcounts(v1,[unique(v1),inf]);
b = ones(1,sum(a));
a = a(1:end-1);
b(cumsum(a)+1) = b(cumsum(a)+1) - a;
b = cumsum(b);
Run Code Online (Sandbox Code Playgroud)


gno*_*ice 5

假设V1已经排序,这是一个矢量化解决方案,使用accumarray:

V2 = accumarray(V1, 1, [], @(x) {1:numel(x)});
V2 = [V2{:}].';
Run Code Online (Sandbox Code Playgroud)


Lui*_*ndo 5

基于这个答案中的第二种方法:

t = diff([0; find([diff(V1)~=0; true])]);
V2 = ones(sum(t), 1);
V2(cumsum(t(1:end-1))+1) = 1-t(1:end-1);
V2 = cumsum(V2);
Run Code Online (Sandbox Code Playgroud)