twfx
twfx

Reputation: 1694

filter floating point in matrix or cell array

The cell array consists of 400x1 elements in double (and may extend to 1,000,000 x 1). I would like to filter all entry with -1.000. What is the best way to filter floating value? Should I do it in cell array or matrix? Or should I do it by just creating a for loop, runs through each element, and store non -1.000 entry into new array?

I read the value from file using textscan, and later convert it to matrix in order to plot a cdf graph. However I'd like to eliminate all entry with -1 from the graph.


fid = fopen('t1_error.txt','r');
C = textscan(fid, '%.3f');            
fclose(fid);

A = cell2mat(C);
[ycdf,xcdf] = cdfcalc(A);
ycdf = ycdf(2:length(ycdf));
plot(xcdf, ycdf, 'LineWidth', 2);

Upvotes: 0

Views: 247

Answers (3)

Ansari
Ansari

Reputation: 8218

You can simply do something like

tolerance = 1e-6;
A(A+1 < tolerance) = [];

to filter out the values that are very close to -1 after setting the tolerance to some acceptable value for your application.

Upvotes: 0

Brian L
Brian L

Reputation: 3251

@Ansari has the right idea, but I'm pretty sure in your case there is no need to look at the tolerance since -1 is a flag for an invalid value, and is represented exactly in floating point, and therefore you won't get any weird rounding issues which the tolerance trick is meant to resolve.

Z = (A == -1);   % Z(i) = 1 if A(i) == -1,
                 %        0 otherwise

A1 = A(~Z);      % Subset of A excluding all -1 values.

Upvotes: 1

CTZStef
CTZStef

Reputation: 1715

you NEVER write a for loop in Matlab, unless you tried every other possibilities ;) Remember, it is matrix oriented programming.

If you want to filter out -1, just do :

A = magic(6);
A(1,3) = -1.23;
A(2:4,3:5) = -1.00;
% the -1.23 value is preserved by the following line
A(A==-1.0000) = 0;

Or if you want to know where those -1 are :

A = magic(6);
A(2:4,3:5) = -1;
minus_one_loc = find(A == -1);
A(minus_one_loc) = 0;

So, this is the answer if I understand well what you wanted.

cheers

Upvotes: 0

Related Questions