In Mathematica, I have a matrix 'a' with missing values and I have a matrix 'b' with same dimension as 'a'. I would like to calculate a-b but if the value is missing, which I denote by 'NA', I would like it to remain as 'NA'. Could you please help me with this? Please note that 'a' is of the dimension 1millionX300.
Thanks!
We can only add or subtract matrices if their dimensions are the same. To add matrices, we simply add the corresponding matrix elements together. To subtract matrices, we simply subtract the corresponding matrix elements together. Not only can we add and subtract matrices, but we can solve matrix equations as well.
One approach would be to use a replacement rule on the result, something like this;
In[1] {1, na, 3, na, 5} - {1, 2, 3, 4, 5}
Out[1] {0, -2 + na, 0, -4 + na, 0}
In[2] {1, na, 3, na, 5} - {1, 2, 3, 4, 5}/. x_ + na -> na
Out[2] {0, na, 0, na, 0}
Another approach would be to define an UpValue
for na
such that addition (and subtraction) involving it would always result in na
; like this:
In[3] na /: Plus[___, na, ___] := na
UpValues
would be the way to go if you are going to do the operation more than once, replacement rules for a one-off.
You could use Indeterminate
for this, since it already has the behavior your looking for:
In[2]:= {1, na, 3, na, 5} - {1, 2, 3, 4, 5} /. na -> Indeterminate /. Indeterminate -> na
Out[2]= {0, na, 0, na, 0}
Personally, I'd just use Indeterminate
to start with, instead of NA
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With