Domanda

Given,

a = [2 4 6 8 10 0 7 18 9 0 8 2 0 5];
b = [1 3 0 5 70 8 6 87 1 9 7 8 0 2];

I am trying to delete elements (in both 'a' & 'b') that corresponds to '0' or less than '0' in either 'a' or 'b' i.e., I want

 % a = [2 4 8 10 7 18 9 8 2 5];
 % b = [1 3 5 70 6 87 1 7 8 2];

I am trying like this -

n = length(b);

a1 = [];
b1 = [];

for k = 1:n
    if a(n) <= 0 || b(n) <= 0 
        a1 = [a; a(a > 0)]   % eliminates 0 from a
        b1 = [b; b(b > 0)]   % eliminates 0 from b
    end
end

Any help will be very helpful.

È stato utile?

Soluzione

Use find:

a = [2 4 6 8 10 0 7 18 9 0 8 2 0 5];
b = [1 3 0 5 70 8 6 87 1 9 7 8 0 2];

A = a( find( a > 0 & b > 0 ) );
B = b( find( a > 0 & b > 0 ) );

or even faster:

C = a(  a > 0 & b > 0  );
D = b(  a > 0 & b > 0  );

returns:

C =

     2     4     8    10     7    18     9     8     2     5
D =

     1     3     5    70     6    87     1     7     8     2

If you can be sure, that there are no values below zero you could also use:

E = a( logical(a) & logical(b) );
F = b( logical(a) & logical(b) );

which is a little faster, but containing also negative values.

Altri suggerimenti

The efficient and compact way to do this is to first create the relevant index, that prevents double calculation:

idx = a>0 & b>0

a = a(idx); 
b = b(idx); 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top