在Matlab向量或矩阵的特定位置插入值 [英] Insert value at a specific spot in matlab vector or matrix
本文介绍了在Matlab向量或矩阵的特定位置插入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在另一个向量中指定的特定索引处向向量插入一个值,然后相应地替换其他值.
I'm trying to insert a value to a vector at specific indices, specified in another vector, and then displacing the other values accordingly.
例如
Vector=[1 2 3 4 5] %vector of data
Idx=[2 4] %Indices at which to insert a value
Value to insert is X
NewVector=[1 X 2 X 3 4 5]
是否有一些简单的方法可以做到这一点,最好避免循环?
Is there some straightforward way to do that, preferably avoiding a loop?
推荐答案
Vector=1:5;
Idx=[2 4];
c=false(1,length(Vector)+length(Idx));
c(Idx)=true;
result=nan(size(c));
result(~c)=Vector;
result(c)=42
result =
1 42 2 42 3 4 5
如果要在已删除的注释中插入新值,请执行以下操作:
If you wanted the new values inserted as in your deleted comment, do this:
c(Idx+(0:length(Idx)-1))=true;
这篇关于在Matlab向量或矩阵的特定位置插入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文