arrays - 从没有循环的两个数组元素成对创建数组

标签 arrays matlab vector vectorization

<分区>

这里是一个简单的问题。我有数组:

a = [ 600 746 8556 90456 ]
b = [ 684 864 8600 90500 ]

我想得到:

output = [ a(1):b(1) a(2):b(2) a(3):b(3) a(4):b(4) ]

(或 [ a(1):b(1); a(2):b(2); a(3):b(3); a(4):b(4) ] ,我不在乎)

如果不使用循环,我不知道如何做到这一点,但我知道这应该是一种方法。

有什么想法吗?

提前致谢

最佳答案

方法 #1

矢量化方法 bsxfun的屏蔽能力 -

%// Get "extents" formed with each pair of "a" and "b" and max extent
ext = b-a
max_ext = max(ext)

%// Extend all a's to max possible extent
allvals = bsxfun(@plus,a,[0:max_ext]')  %//'

%// Get mask of valid extensions and use it to have the final output
mask  = bsxfun(@le,[0:max_ext]',ext)  %//'
out  = allvals(mask).'

方法 #2

此处列出的是 cumsum基于方法,必须比之前列出的基于 bsxfun 的方法和 arrayfun based approach in the other answer 具有更高的内存效率和更快的速度.这是代码-

%// Get "extents" formed with each pair of "a" and "b"
ext = b-a;

%// Ignore cases when "a" might be greater than "b"
a = a(ext>=0);
b = b(ext>=0);
ext = b-a;

if numel(ext)>1

    %// Strategically place "differentiated" values from array,a
    idx = ones(sum(ext+1),1);
    idx([1 cumsum(ext(1:end-1)+1)+1]) = [a(1) diff(a)-ext(1:end-1)];

    %// Perform cumulative summation to have the final output
    out = cumsum(idx)

else %// Leftover cases when there are one or no valid boundaries:(a->b)
    out = a:b
end

sample 运行-

>> a
a =
     6    12    43
>> b
b =
     8    17    43
>> out
out =
     6     7     8    12    13    14    15    16    17    43

关于arrays - 从没有循环的两个数组元素成对创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973005/

相关文章:

vector - VHDL 直接比较向量

java - 在 C++ 与 Java 中利用对象的巨大 vector (或数组?)的最快方法

javascript - 如何访问 Angular 4中另一个对象数组内的对象数组

ios - 如何在新数组中捕获过滤后的值

python - 将 Matlab 代码翻译成 Numpy

python - 我可以在 python 交互模式下有多个 matplotlib 绘图窗口吗?

java - 使用 MARF 进行说话人识别

c - 打印通过指针 C 发送的字符串

PHP数组映射

for-loop - 如何在循环内创建向量的向量?