Substracting all elements in two arrays with different sizes

1 vue (au cours des 30 derniers jours)
KuriGohan
KuriGohan le 1 Avr 2022
Commenté : KuriGohan le 1 Avr 2022
I would like to substract each element in array 1 from each element in array 2. The arrays have different sizes. Basically i would like to achive this:
a1 = (1, 2)
a2 = (1, 2, 3)
a_result = (1-1, 2-1 ,1-2 , 2-2, 1-3, 2-3)
Any tips on how to do this?

Réponse acceptée

Riccardo Scorretti
Riccardo Scorretti le 1 Avr 2022
Modifié(e) : Riccardo Scorretti le 1 Avr 2022
Enjoy ...
a1 = [1 2];
a2 = [1 2 3];
res = a1.' - a2 ; res = res(:).'
res = 1×6
0 1 -1 0 -2 -1
Pay attention to the fact that a1 and a2 must be row-vectors (= not column-vectors), otherwise you will have to modify a little bit.
The general idea is that a1.' is a column vector, and a2 is a row-vector. In Matlab colum-vector (op) row-vector returns a matrix, the entries of which are the result of the operation between each couple of elements of the two vectors.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by