[英]Insert value at a specific spot in matlab vector or matrix
I'm trying to insert a value to a vector at specific indices, specified in another vector, and then displacing the other values accordingly. 我正在尝试在另一个向量中指定的特定索引处向向量插入一个值,然后相应地替换其他值。
Eg 例如
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;
Here is a general function. 这是一个常规功能。 The idea is the same as @Mark said:
这个想法与@Mark所说的相同:
function arrOut = insertAt(arr,val,index)
assert( index<= numel(arr)+1);
assert( index>=1);
if index == numel(arr)+1
arrOut = [arr val];
else
arrOut = [arr(1:index-1) val arr(index:end)];
end
end
I have never heard of a built-in function for this. 我从未听说过内置函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.