Im looking for a way to add up elements of two arrays

痞子三分冷 提交于 2019-12-13 09:58:21

问题


i am looking for a way that i can add up elements in an array such that the first element of the first array is added to every element in the second array, then the second element in the first array is added to all every element in the second array and so on. The final vector will be length(a)*length(b) long

for example...

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]


回答1:


My first thought is to do this with arrayfun using an anonymous function that adds each scalar element of a to the full array in b. Then since you get a cell array result you can expand that cell array into the array you are looking for:

>> 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:


Read up on bsxfun. It's very useful for this kind of things (and usually faster than arrayfun or for loops):

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

Or, a little more freak: kron does what you want with products instead of sums. So:

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



回答3:


Use meshgrid to create matrices of a and b and use matrix addition to compute 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(:)'


来源:https://stackoverflow.com/questions/22158727/im-looking-for-a-way-to-add-up-elements-of-two-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!