I am trying to do element by element subtraction like the following:
a= [1,2,3,4,5] b= [-1,-2,-3]
I would like my output to be "a" to be subtracted by the first element of "b" then by the second element and so on. The output "c" should look like: c=[2,3,4,5,6,3,4,5,6,7...]
I understand that if I simply do "c=a-b" will not work because the dimensions do not agree. Would something like this require a loop?

 採用された回答

Image Analyst
Image Analyst 2017 年 12 月 10 日

1 投票

Try this:
a= [1,2,3,4,5]
b= [-1,-2,-3]
c = a' - b;
c = c(:)'
You get
c =
2 3 4 5 6 3 4 5 6 7 4 5 6 7 8
in R2016b (I believe) or later that has automatic expansion capability.

3 件のコメント

Image Analyst
Image Analyst 2017 年 12 月 10 日
If you need/want it in one line of code instead of 2, you can use
c = reshape(a' - b, 1, [])
If that doesn't work for you because you have an old version of MATLAB, let me know.
anuforo peter
anuforo peter 2020 年 3 月 7 日
What about doing this on a mutidimensional array
anuforo peter
anuforo peter 2020 年 3 月 7 日
Please help! Thank you ?

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

その他の回答 (1 件)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017 年 12 月 10 日

0 投票

minus operator in Matlab can inherently handle this, so you don't need a loop. Checkout >> help minus. For your case, something like this will work.
a= [1,2,3,4,5]; b= [-1,-2,-3];
c = reshape(a'-b,1,numel(a)*numel(b));

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by