MATLAB: Subtraction of 2 plots with negative and positive values at different points.

dataMATLABplot

Hi all,
I've these 2 plots, let say A and B.
Both A and B contains 1 column and 41 rows of values (some positive and some negative).
My objective is to subtract A (reference values) from B (calculated values). Since some values in A or B can be of different signs, I'll have to perform the "offset" such that when:
A is -ve and B is +ve, it will perform an addition instead. A is -ve and B is -ve, it will perform an subtraction. A is +ve and B is +ve, it will perform an subtraction. A is +ve and B is -ve, it will perform an addition.
For example,
A = -1, B = 0.5 –> B – A = -0.5
Can anyone please help? Thanks.

Best Answer

A=[1 2 -3 -4]
B=[10 -20 30 -40]
idx=sign(A.*B)
out=A-B.*idx