Borrar filtros
Borrar filtros

Element by Element Subtraction

51 visualizaciones (últimos 30 días)
Sanim Rahman
Sanim Rahman el 10 de Dic. de 2017
Comentada: anuforo peter el 7 de Mzo. de 2020
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?

Respuesta aceptada

Image Analyst
Image Analyst el 10 de Dic. de 2017
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 comentarios
anuforo peter
anuforo peter el 7 de Mzo. de 2020
What about doing this on a mutidimensional array
anuforo peter
anuforo peter el 7 de Mzo. de 2020
Please help! Thank you ?

Iniciar sesión para comentar.

Más respuestas (1)

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan el 10 de Dic. de 2017
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));

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by