Reputation: 25
i have a matrix B{1} =[1.1 1.1 1.0 ; 0.8 0.9 1.2 ; 0.9 0.9 1.5] I have found that the overall median of the matrix is 1.0.
Next i want to go through every element in the matrix and compare it with the median. If the element exceeds the error threshold value of 0.1, the element will be replaced by zero. If the element is equal or lesser than 0.1, the element value will remain.
After going through the coding below, i am expecting my end result of B{1} to be [1.1 1.1 1.0 ; 0.0 0.9 0.0 ; 0.9 0.9 0.0].
However the output of the coding below gives B{1}=[ 0.0 0.0 1.0 ; 0.0 0.9 0.0 ; 0.9 0.9 0.0]
for x=1:9
matrix=B{1};
excess = abs(minus(matrix(x),1.0))
if excess > 0.1
matrix(x)=0;
B{1}=matrix;
end
end
Any idea where is the mistake(s) in the coding?
Upvotes: 1
Views: 231
Reputation: 221714
You are running into precision issue, which can be avoided by adding a little tolerance into it. With that change, you can have a vectorized solution to this -
B{1} =[1.1 1.1 1.0 ; 0.8 0.9 1.2 ; 0.9 0.9 1.5]
matrix=B{1};
TOL = 0.001;%%// Tolerance to account for precision issue
matrix(abs(bsxfun(@minus,matrix,median(matrix(:))))>0.1+TOL)=0;
B{1} = matrix;
In your code, you could have done the same with this -
TOL = 0.001;%%// Tolerance to account for precision issue
excess = abs(minus(matrix(x),1.0+TOL))
Edit 1: You can add a matrix dependent tolerance to it, by using this (thanks to @bdecaf on this) -
TOL = max(eps(matrix(:)))
Upvotes: 1