adding every element of an array with every element of another array?

dear all, i want to add array elements to every other element of another element of another array in simulink/matlab

 採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 11 月 30 日

1 投票

Pranav wrote: "...i want to add elemnts of A to be added to every other elemnet of B. ie. 1+[5 6 7 8],2+[5 6 7 8],...so on..."
A = [ 1 2 3 4];
B = [ 5 6 7 8];
C = reshape(bsxfun(@plus,A,B.'),1,[]);

その他の回答 (3 件)

Vishal Rane
Vishal Rane 2012 年 11 月 30 日
編集済み: Vishal Rane 2012 年 11 月 30 日

0 投票

Do you need to do this in MATLAB code ?
A = [ 1 2 3 4]
B = [ 5 6 7 8]
C = A + B = [ 6 8 10 12 ]
Comment back if your requirement is different.

3 件のコメント

Pranav
Pranav 2012 年 11 月 30 日
Thanks but sorry.i want to add elemnts of A to be added to every other elemnet of B. ie. 1+[5 6 7 8],2+[5 6 7 8],...so on
Vishal Rane
Vishal Rane 2012 年 11 月 30 日
arrayfun(@(x)(x+A),B,'Un',0)
will work in that case but output will be a 1x4 cell arrray.
Pranav
Pranav 2012 年 12 月 3 日
Thanks Vushal i will check for other array sizes.

サインインしてコメントする。

Matt Fig
Matt Fig 2012 年 11 月 30 日

0 投票

A = 0:4;
B = 10:16;
bsxfun(@plus,A,B')

1 件のコメント

Pranav
Pranav 2012 年 12 月 3 日
Thanks u Matt fot the solution. I shall convert it into a row vector.

サインインしてコメントする。

Brandon
Brandon 2016 年 5 月 9 日
編集済み: Brandon 2018 年 12 月 11 日

0 投票

I found this conversation while looking for a faster way to accomplish this task. The code below also works but is just slightly slower in my code on my machine.
X=[A' ones(size(A'))];
Y=[ones(size(B)); B];
reshape(X*Y,1,[])

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

タグ

質問済み:

2012 年 11 月 30 日

編集済み:

2018 年 12 月 11 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by