我在 Matlab 中有一个包含 13 个实体的向量。
a=[3 4 6 8 1 5 8 9 3 7 3 6 2]
我想在位置 1 5 9 13 和 17 处定期 append 值 [1 2 3 4 5]
。
a 的最终值如下所示。
a=[1 3 4 6 2 8 1 5 3 8 9 3 4 7 3 6 5 2]。
斜体值显示 append 值。 我该怎么做?
最佳答案
由于您正在寻找规则的间隔,因此可以利用 reshape
和 cat
函数:
a = [3 4 6 8 1 5 8 9 3 7 3 6 2];
v = [1 2 3 4 5];
l = [1 5 9 13 17];
interval = l(2)-l(1)-1; %computes the interval between inserts
amax = ceil(size(a,2)/interval) * interval; %calculating maximum size for zero padding
a(amax) = 0; %zero padding to allow `reshape`
b = reshape (a,[interval,size(v,2)]); %reshape into matrix
result = reshape(vertcat (v,b), [1,(size(b,1)+1)*size(b,2)]); %insert the values into the right position and convert back into vector
%remove padded zeros
final = result(result ~= 0) %remove the zero padding.
>>final =
第 1 至 16 列
1 3 4 6 2 8 1 5 3 8 9 3 4 7 3 6
第 17 至 18 列
5 2
关于matlab - 如何在Matlab中定期向向量中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38845713/