【问题标题】:Creating a vector创建矢量
【发布时间】:2012-03-25 11:54:24
【问题描述】:

输出向量应如下所示:

a=[3 3 3 4 4 4 4 5 5 5 5 5]

我拥有的是:

pe=[1 5 9] and ne=[4 8 12] and co=[3 4 5]

pe 描述了每个条目的起始索引和 ne 结束索引,并与该条目的值相关

我想在没有循环的情况下执行此操作。 使用 Loop 它应该是这样的:

  for i=1:3
     a(pe(i):ne(i))=co(i)
   end

【问题讨论】:

  • for i 循环应该是 pe(i) ... 等等,对吧?另外,您想如何处理 pe=[1 4 9] 和 ne=[6 8 12] 和 co=[3 4 5] 的情况?使用最新值?
  • 是..我的错对不起..它必须是(pe(i):ne(i))=co(i)。在另一种情况下,我只想用pe创建, ne 和 co 来自上面的向量 a。这意味着:pe 的第一个条目是 a 中 co(1)=3 的第一个条目,pe 的第一个条目是 a 中 co(1))=3 的最后一个条目,依此类推。 ..

标签: matlab vector indexing vectorization


【解决方案1】:

一种方法是首先使用cumsumco中创建一个索引数组

idxList = zeros(1,max(ne)); %# create an array with zeros
idxList(pe) = 1;            %# mark the start of a new index
idxList = cumsum(idxList);  %# now, idxList has 1's where we should
                            %# place the first element of co, etc
out = co(idxList);          %# and we're done. 

【讨论】:

  • 谢谢!基本上就是这么简单,但我没想到!
  • @HakanKiyar:不客气。如果您觉得答案有帮助,请考虑接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多