Element by Element Subtraction

51 次查看(过去 30 天)
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
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 个评论
anuforo peter
anuforo peter 2020-3-7
What about doing this on a mutidimensional array

请先登录,再进行评论。

更多回答(1 个)

Kaushik Lakshminarasimhan
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));

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by