【问题标题】:for loop to correlate and edit vectorsfor 循环关联和编辑向量
【发布时间】:2018-10-15 15:18:31
【问题描述】:

我需要在 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

【问题讨论】:

  • 很不清楚你在问什么。第一部分的答案,在代码之前是y2=y(1:end-shift); q2=q(shift:end) 我不明白代码是如何与此相关的。
  • 请忽略 y 和 q 部分,这只是一个示例。真正的代码如下。
  • 如果您希望我们忽略qy 部分,为什么将其包含在问题中?我了解您在qy 部分中的要求,但我不了解代码,这与从数组中删除元素有何关系。看起来您正在尝试计算 sound1sound2 之间的互相关,但您为每个班次添加了不同的噪声,这很奇怪。要计算互相关,请使用conv。或者使用fftas here
  • @MatCode 请仅添加有关您的问题的相关信息

标签: matlab for-loop vector


【解决方案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);

【讨论】:

  • 为什么插入NaN然后使用nansum,而不是仅仅删除你不需要的元素as suggested by Ander
  • 我建议使用这种方法,因此只需要操作“y”向量,但任何一种都可以。
  • 啊,有道理。好主意!请注意,从 R2018b(或者是 R2018a?)开始,您可以使用 sum(A,'omitnan'),如果您没有 nansum(它需要工具箱)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 2022-11-04
  • 2019-05-17
相关资源
最近更新 更多