元素智能阵列复制根据计数 [英] Element-wise array replication according to a count

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

问题描述

我的问题是类似于此 之一,但我想根据在相同尺寸的第二阵列指定的计数复制的每个元素

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] ,我想用代表= [2 3 1 5] 来复制所述第一元件的2倍,二三次,依此类推,以获得 [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

我设法preallocating空间来改善:

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

这通过首先创建零的索引向量相同的长度的所有值的最后计数。通过执行代表的累加值与放置在开始的1去掉最后一个元素和载体,我得到指数的载体导入指数表示将复制值的组将开始。这些点都标有的。当首页执行的累加值,我得到一个最终的指数矢量,我可以使用索引到 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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆