【问题标题】:Replicate elements from an array into a different array in Matlab将数组中的元素复制到Matlab中的不同数组中
【发布时间】:2018-12-03 04:36:17
【问题描述】:

在 Matlab 中,我有一个数组 "latencies"(大小 1x11)和一个元胞数组 "Latencies_ms"(大小 1x298)。 latenciesLatencies_ms 的一小部分,即latencies 中的值存在于Latencies_ms 中。我希望能够在Latencies_ms 内的latencies 中找到每个值,然后将1000 添加到该值并在Latencies_ms 内重复此8 次。

例如,

latencies = [62626  176578  284690  397708  503278  614724  722466] 

和(Latencies_ms 的小样本)

Latencies_ms = {3458, 62626, 123456, 7891011, 121341, 222112, 176578}

我希望输出是

out = {3458, 62626, 63626,  64626,  65626,  66626,  67626,  68626,  69626,  70626, 123456, 7891011, 121341, 222112, 176578, 177578, 178578, 179578, 180578, 181578, 182578, 183578, 184578,}

作为一个起点,我决定看看我是否可以在不添加 1000 的情况下复制每个元素,并且我已将以下代码与 repmat 一起使用:

out = arrayfun( @(x,b)[x; repmat({latencies},8,1)],... 
Latencies_ms, ismember(cell2mat(Latencies_ms),latencies), 'uni', 0 );
out = vertcat(out4{:});

我将延迟元素与 Latencies_ms 匹配,然后使用 repmat 但是像这样使用它会在正确的位置插入整个 latencies 数组,而不是重复元素。

如果我尝试使用这样的 for 循环:

for i=1:length(latencies)
   out = arrayfun( @(x,b)[x; repmat({latencies(i)},8,1)],... 
   Latencies_ms, ismember(cell2mat(Latencies_ms),latencies), 'uni', 0 );
   out = vertcat(out4{:});
end

它只重复延迟的最后一个元素,因此它正确地进行了复制,而不是正确的元素。

我对@9​​87654339@ 不太精通,我认为它的全部意义在于避免使用 for 循环,所以我确信这不是正确的方法,但我觉得我快到了.. . 有谁知道我错过了什么???

我不必使用 arrayfun,我尝试使用 for 循环来做到这一点,但它有点乱,但没有限制只使用 arrayfun 我只想得到正确的输出!

【问题讨论】:

  • arrayfun 真的只是一个“变相的循环”,你可能会发现用一个完整的循环替换它更容易,这样你会更清楚发生了什么,然后包括额外的操作

标签: arrays matlab for-loop cell bsxfun


【解决方案1】:

这是一个无循环的方式:

ind = ismember([Latencies_ms{:}] , latencies);      %Indices of the values to be repeated
repvals = bsxfun(@plus, repmat([Latencies_ms{ind}], 9, 1).', 0:1000:8000); %Rep+increment
out = Latencies_ms;
out(ind) = mat2cell(repvals, ones(1, sum(ind)), 9); %Replacing with repeated+inc elements
out = [out{:}]; %Converting to comma-separated list and then concatenating horizontally

第 2 行和第 4 行中的因子 9 存在,因为匹配的元素将保留一次并以增量重复 8 次(总计 = 9 次)。第二行可以用≥ R2016b 中的隐式扩展写成:

repvals  = repmat([Latencies_ms{ind}], 9, 1).' + (0:1000:8000);

arrayfun 是循环的单行包装器。它仍然是一个循环。但是循环在较新的版本(从 R2015b 开始)中得到了显着改进,有时它们的性能甚至超过了矢量化代码。所以没有必要避免一个简单的循环,你可以理解复杂的矢量化,除非它是一个瓶颈。

【讨论】:

  • 谢谢!我正在通过循环重新创建它,但到目前为止还没有成功,但这个解决方案现在可以满足我的需要!
  • 再次非常感谢,我已经对它进行了更多的修改并对其进行了修改,以便我能够根据需要将它包含在一个循环中,并且我更好地理解了整个 bsxfun并且 arrayfun 正在工作!
  • @MaheenSiddiqui 你基本上需要bsxfunarrayfun?我不明白为什么
  • 有一点我需要在单元格中进行操作,以便更容易使用 bsxfun,我并不完全了解它是如何工作的,但现在我知道了
猜你喜欢
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
相关资源
最近更新 更多