如何在Matlab中以固定间隔在向量中插入元素 [英] How to insert elements in a vector at regular intervals in Matlab

查看:49
本文介绍了如何在Matlab中以固定间隔在向量中插入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Matlab 中有一个包含 13 个实体的向量.

I have a vector of 13 entities in Matlab.

a=[3 4 6 8 1 5 8  9  3 7 3 6 2]

我想在位置 1 5 9 13 & 以固定间隔附加值 [1 2 3 4 5]17.a 的最终值如下所示.

I want to append values [1 2 3 4 5] at regular intervals at position 1 5 9 13 & 17. The final value of a looks like this.

a=[1 3 4 6 2 8 1 5 3 8 9 3 4 7 3 65 2].

a=[1 3 4 6 2 8 1 5 3 8 9 3 4 7 3 6 5 2].

斜体的值表示附加的值.我该怎么做?

The values with italics show the appended values. How can I do it?

推荐答案

由于您正在寻找固定间隔,您可以利用 reshapecat 功能:

Since you are looking for regular intervals, you can take advantage of the reshape and cat function:

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 列

Columns 1 through 16

 1     3     4     6     2     8     1     5     3     8     9     3     4     7     3     6

第 17 至 18 列

Columns 17 through 18

 5     2

这篇关于如何在Matlab中以固定间隔在向量中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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