本文介绍了根据计数按元素进行数组复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题类似于这个一个,但我想根据在相同大小的第二个数组中指定的计数复制每个元素.

My question is similar to this one, but I would like to replicate each element according to a count specified in a second array of the same size.

一个例子,假设我有一个数组 v = [3 1 9 4],我想用 rep = [2 3 1 5] 来复制第一个元素2次,第二个3次,依此类推得到[3 3 1 1 1 9 4 4 4 4 4].

An example of this, say I had an array v = [3 1 9 4], I want to use rep = [2 3 1 5] to replicate the first element 2 times, the second three times, and so on to get [3 3 1 1 1 9 4 4 4 4 4].

到目前为止,我正在使用一个简单的循环来完成工作.这就是我的开始:

So far I'm using a simple loop to get the job done. This is what I started with:

vv = [];
for i=1:numel(v)
    vv = [vv repmat(v(i),1,rep(i))];
end

我设法通过预分配空间来改进:

I managed to improve by preallocating space:

vv = zeros(1,sum(rep));
c = cumsum([1 rep]);
for i=1:numel(v)
    vv(c(i):c(i)+rep(i)-1) = repmat(v(i),1,rep(i));
end

但是我仍然觉得必须有一个更聪明的方法来做到这一点...谢谢

However I still feel there has to be a more clever way to do this... Thanks

推荐答案

这是我喜欢的一种方法:

Here's one way I like to accomplish this:

>> index = zeros(1,sum(rep));
>> index(cumsum([1 rep(1:end-1)])) = 1;

index =

     1     0     1     0     0     1     1     0     0     0     0

>> index = cumsum(index)

index =

     1     1     2     2     2     3     4     4     4     4     4

>> vv = v(index)

vv =

     3     3     1     1     1     9     4     4     4     4     4

首先创建一个由零组成的索引向量,其长度与所有值的最终计数相同.通过执行 rep 向量的累积和,最后一个元素被删除,1 放在开头,我得到一个索引向量到 index 中,显示复制组的位置值将开始.这些点用 1 标记.当对 index 执行累积求和时,我会得到一个最终的索引向量,我可以用它来索引 v 以创建异构复制值的向量.

This works by first creating an index vector of zeroes the same length as the final count of all the values. By performing a cumulative sum of the rep vector with the last element removed and a 1 placed at the start, I get a vector of indices into index showing where the groups of replicated values will begin. These points are marked with ones. When a cumulative sum is performed on index, I get a final index vector that I can use to index into v to create the vector of heterogeneously-replicated values.

这篇关于根据计数按元素进行数组复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 03:41