for循环关联和编辑向量

时间:2018-10-15 15:18:31

标签: matlab for-loop vector

我需要在2个变量中编辑矢量,以使它们彼此对应。

For example, 
y = 1 2 3 4 5 6
q = 8 26 1 5 1 6

Let's say I fix q and shift y by 1
y =    1 2 3 4 5 6
q = 8 26 1 5 1 6

I need vector y1 = 1 2 3 4 5 and q1 = 26 1 5 1 6
This means I need to kick out 6 in y and 8 in q respectively.

Let's say I fix q and shift y by 2
y =      1 2 3 4 5 6
q = 8 26 1 5 1 6
As before, now I need to remove 5,6 in y and 8,26 in q respectively.

我想在for循环中执行此操作,因为我的向量很长。现在,我正努力使向量正确地适合q(这是我的soundtwo),如下所示。有提示吗?

% Creating time vector, "t"
t = linspace(0,16*pi,1000);

sound1 = 5*(cos(t) + 1*(rand(size(t))-0.5));
sound2 = 8*(cos(t) + 1.5*(rand(size(t))-0.5));

% Setting the time shift "dt"
dt = 1000;

% Creating a matrix to store product later on
list = zeros(dt,1);

% For loop for different shifts
for i=1:dt

      % Now edit sound1 such that sound1 shifts while sound2 remains unchanged
      %different time shift

      sound1 = 5*(cos(t+ i ) + 1*(rand(size(t))-0.5));
      sound2 = 8*(cos(t) + 1.5*(rand(size(t))-0.5));

      % Shifting sound1
      soundone = sound1(i:numel(sound1))

      % Sound 2 unchanged, but have to assign respective vector to sound1
      soundtwo = sound2()

      multipliedsound = (soundone) .* (soundtwo);

      add = sum(multipliedsound)

      product = add  / numel(t);

      % Append product to list vector
      list(i,1) = product;

end

1 个答案:

答案 0 :(得分:1)

函数circshift将旋转y的值,然后可以设置旋转的NaN值。将y的旋转值设置为NaN无需再更改或删除q中的值:具有NaN的乘积值也将为NaN,然后​​被NaN sum忽略。下面的示例将值移位2,但是您可以轻松替换其他移位值。

y = [1 2 3 4 5 6];
q = [8 26 1 5 1 6];

shift_value = 2;

y_shifted = circshift(y, shift_value);
y_shifted(1:shift_value) = NaN;

product_value = y_shifted .* q;
sum_value = nansum(product_value);