Tosmai
Tosmai

Reputation: 60

Truncating an array

A simplified version of my code is as follows:

A = linspace(0,10,100);
threshold = 6.0;

I'd like to truncate the vector A at values below the threshold value.

Assuming that the values in A are always ascending, how can I do this neatly and efficiently?

Currently the only method I can think of is to introduce a for-loop and examine each element, one after another and if it has a value above the threshold, and then to allocate this value to a new array. Something like this:

    k=1;
    for i = 1:numel(A)
        if A(i) < threshold
        elseif A(i) >= threshold
            Atrunc(k,1) = A(i);
            k=k+1;
        end
    end 

However this doesn't seem very 'nice' to me, can anybody offer more optimized code...?

Upvotes: 0

Views: 1535

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112749

Since the values in A are ascending, you can use binary search to find the last element below the threshold:

threshold = 5; %// example data
A = linspace(0,15,1e7); %// example data

w = [1 numel(A)]; %// uncertainty window. Initiallize
while w(2)>w(1)+1
    t = round((w(1)+w(2))/2); %// test middle point
    if A(t)<threshold
        w(1) = t; %// remove lower half of window
    else
        w(2) = t; %// remove upper half of window
    end
end
if A(w(2)) < threshold %// handle special cases: Atrunc is A or is []
    t = w(2);
elseif A(w(1)) < threshold 
    t = w(1);
else
    t = w(1)-1;
end
Atrunc = A(1:t);

For A large this approach (which exploits the fact that A is sorted) may be faster than Atrunc = A(A < threshold);

Upvotes: 0

MattyG
MattyG

Reputation: 66

Use logical indexing

A = A(A < threshold);

or

A = A(A >= threshold);

Upvotes: 2

Related Questions