MATLAB: HOW TO COMPARE TWO ARRAYS ELEMENTS IN MATLAB

compare arraysnansign function

I had an array AA = [ 0.1, 0.2, 0.3, 0.2, 0.1, -0.1, -0.2, -0.3]. Then I got two arrays one shifted left one element and the other shifted right one element and padded with NaN accordingly. Example: shifted versions of arrays aa = [0.2, 0.3, 0.2, 0.1, -0.1, -0.2, -0.3, NaN] and second array as bb = [NaN, 0.1, 0.2, 0.3, 0.2, 0.1, -0.1, -0.2].
I want to compare these arrays and put the result in another array of same size,such that during comparison if the compared elements have the same sign (-/- or +/+) then the new resulted array should get NaN for that comparison entry and if the signs of the compared elements is different(-/+ or +/-), then keep the original value of the original array from where I started i.e AA.
Something like this, after comparing sign of each element of aa and bb, I should get something like this:
result = [ NaN, NaN, NaN, NaN, 0.1, -0.1, NaN, NaN]
I got the shifted versions, I just want to get some idea about comparison described above.

Best Answer

aa = [0.2, 0.3, 0.2, 0.1, -0.1, -0.2, -0.3, nan]
bb = [nan, 0.1, 0.2, 0.3, 0.2, 0.1, -0.1, -0.2]
idx=arrayfun(@sign ,aa.*bb)
AA(find(idx==1 | isnan(idx)))=nan