Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica subtracting matrices with missing value

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!

like image 795
user1050325 Avatar asked Jun 10 '12 18:06

user1050325


People also ask

Can you subtract matrices?

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.


2 Answers

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.

like image 146
High Performance Mark Avatar answered Oct 19 '22 15:10

High Performance Mark


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.

like image 4
Brett Champion Avatar answered Oct 19 '22 16:10

Brett Champion