我正在寻找一种方法来添加两个数组的元素

时间:2014-03-03 22:19:55

标签: arrays matlab addition

我正在寻找一种方法,我可以在一个数组中添加元素,使第一个数组的第一个元素添加到第二个数组中的每个元素,然后第一个数组中的第二个元素添加到所有每个元素第二个数组中的元素,依此类推。最终的载体将是长度(a)*长度(b)长

例如......

a=[1,2,3,4] b=[5,6,7] answer = [(1+5),(1+6),(1+7),(2+5),(2+6),(2+7),(3+5),(3+6),(3+7),(4+5),(4+6),(4+7)] =[6,7,8,7,8,9,8,9,10,9,10,11]

3 个答案:

答案 0 :(得分:5)

阅读bsxfun。它对于这类事物非常有用(并且通常比arrayfunfor循环更快):

result = bsxfun(@plus, a(:).', b(:)); %'// matrix of size numel(b) x numel(a)
result = result(:).'; %'// linearize to a vector

或者,更多一点怪人:kron用产品做你想要的而不是总和。所以:

result = log(kron(exp(a),exp(b)));

答案 1 :(得分:3)

我的第一个想法是使用一个匿名函数对arrayfun执行此操作,该函数将a的每个标量元素添加到b中的完整数组中。然后,因为您获得了单元格数组结果,您可以将该单元格数组扩展到您要查找的数组中:

>> a=[1,2,3,4], b=[5,6,7]
>> result = arrayfun(@(x) x+b, a,'UniformOutput',false);
>> result = [result{:}]

result =

     6     7     8     7     8     9     8     9    10     9    10    11

答案 2 :(得分:1)

使用meshgrid创建a和b的矩阵,并使用矩阵加法来计算a + b

a=[1,2,3,4], b=[5,6,7]

[A_matrix,B_matrix] = meshgrid(a,b)
result = A_matrix + B_matrix

result = result(:)'
相关问题