How to perform mathematical operation between all elements of arrays with unequal numbers

2 ビュー (過去 30 日間)
I have two arrays A & B, being a nXm and a pXq array, repsctively. I want to take A(i,j) and multiply it in or subtract it from all elements of B. Then I will take the next element of A and so on. is it possible to do without using a loop on all elements?

採用された回答

John D'Errico
John D'Errico 2019 年 5 月 24 日
編集済み: John D'Errico 2019 年 5 月 24 日
A = rand(2,3);
B = rand(4,5);
C = A + reshape(B,[1,1,size(B)]); % Addition
C = A - reshape(B,[1,1,size(B)]); % subtraction
size(C)
ans =
2 3 4 5
D = A .* reshape(B,[1,1,size(B)]); % multiplication
D = A ./ reshape(B,[1,1,size(B)]); % division
size(D)
ans =
2 3 4 5
This is possible as long as you have MATLAB release 2016b or later. Earlier releases will need to use bsxfun instead.
help bsxfun
Note that you use .* and ./ for elementwise multiplication/division, not the * or / operators.

その他の回答 (1 件)

Matt J
Matt J 2019 年 5 月 24 日
編集済み: Matt J 2019 年 5 月 24 日
Here is how you would do the subtraction
A-reshape(B,1,1,p,q) %result is nXmXpxq
but it will work equally well with any other operation that supports implicit expansion.

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by