且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数组中的元素复制到Matlab中的另一个数组中

更新时间:2022-04-10 15:56:52

这是一种无循环方式:

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

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

The factor 9 in 2nd and 4th line is there since the matched element is to be kept once and repeated 8 times with increments (total = 9 times). The second line can be written with implicit expansion in ≥ R2016b as:

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

arrayfun 是用于一个循环。这仍然是一个循环。但是循环(从R2015b开始)在较新版本中已得到显着改善,有时它们的性能甚至超过了矢量化代码。因此,除非是瓶颈,否则无需避免复杂的向量化所能理解的简单循环。

arrayfun is a one-line wrapper for a loop. It is still a loop. But loops have been significantly improved in newer versions (starting from R2015b) and sometimes their performance even surpass the vectorised code. So no need to avoid an easy loop that you can understand for complicated vectorisation unless it's a bottle-neck.