Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtracting two matrices in matlab, the negative values in result are substituted by zero

Tags:

matrix

matlab

I have two matrices in matlab,

> IRwindow =
> 
>   **183**  171  150  125  137
    138  167  184  173  152
    105  114  141  167  185  
    148  113  105  115  141  
    186  183  147  112  105
> 
> ILwindow =
> 
>   **201**  170  165  177  203
    181  174  167  169  189 
    154  150  156  168  181 
    187  175  158  131  144 
    173  186  183  167  141

I want to subtract these two matrices element-wise and get the result; for example for first element (183 - 201= -18 ) BUT the output for this element gives zero. the outcome result will be as below:

> IRwindow - ILwindow

 ans =

     **0**    1    0    0    0
     0    0   17    4    0
     0    0    0    0    4
     0    0    0    0    0    
     13    0    0    0    0

how could I keep the real results? without getting zero for negatives in my result-matrix

like image 284
farzin parsa Avatar asked Feb 03 '13 23:02

farzin parsa


1 Answers

Run the following example code:

%# Create random matrices
X = randi(100, 5, 5);
Y = randi(100, 5, 5);

%# Convert to strictly non-negative format
X = uint8(X);
Y = uint8(Y);

%# Perform subtractions
A = X - Y;

%# Convert to double format
X = double(X);
Y = double(Y);

%# Perform subtraction
B = X - Y;

For a given sample run:

A =

    0   15   36    0    0
    0    0    0    0    3
    0    0    0   25    0
   13    0   15    0    0
    0   49    0    0   14

while:

B =

    -8    15    36    -4   -65
     0   -47   -45   -11     3
   -18   -17   -11    25   -52
    13   -53    15   -15    -1
   -35    49   -47    -8    14

You will notice that all the negative numbers in A have been replaced by 0, while the negative numbers in B are displayed correctly.

Stated simply: if you use a numerical format that is not able to store negative numbers, then Matlab truncates at 0. The solution is to convert to a format that is able to accomodate "real" numbers (or a close approximation thereof) such as double, or perhaps in your case one of the int formats may be more appropriate, such as int8, int16, int32 or int64.

like image 182
Colin T Bowers Avatar answered Sep 26 '22 13:09

Colin T Bowers