MATLAB: Element by Element Subtraction

loopMATLABmatrices

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?

Best Answer

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.