matrix logical indexing
Mostra commenti meno recenti
I have a matrix A with dimensions nxm. I want to extract all values x that are between two values a and b, that is: (a<x<b). How can I do it in one step?
I know i can do it in two steps: A1 = A(A>a); A2 = A1(A1<b);
how do I combine the two logical statements?
Risposta accettata
Più risposte (1)
Teja Muppirala
il 13 Set 2011
In the case of checking bounds by combining two logical statements, I think the following expression will generally be significantly faster:
B = A(abs(A-(a+b)/2) < (b-a)/2);
The only thing is, you need to make sure that the datatypes and magnitudes of numbers you are working with can be used in this expression. For example, if you are working with integers, you might get overflow/underflow in some situations, etc. For regular double precision numbers you should probably be ok.
5 Commenti
Jan
il 13 Set 2011
A = rand(1000); a = 0.2, b = 0.6;
tic; z = A(A>a & A<b); toc % 0.0577
tic; z = A(abs(A-(a+b)/2) < (b-a)/2); toc % 0.0443
But why is it faster? With N=numel(A): It uses N*9 bytes as temporary memory, performs N*2 arithemtical operations and compares N values. Fangjun's method needs N*3 bytes as temporary memory and compares N*2 values without arithmetic operations.
Fangjun Jiang
il 13 Set 2011
Interesting but hard to believe. I made an example to dis-prove that. Do you have a count-example?
%%
A=rand(1000);
a=0.2;
b=0.8;
t1=0;
t2=0;
for k=1:100
tic;
A1=A(A>a & A<b);
t1=t1+toc;
tic;
A2=A(abs(A-(a+b)/2) < (b-a)/2);
t2=t2+toc;
end
fprintf('t1=%f\n',t1);
fprintf('t2=%f\n',t2);
t1=4.654067
t2=5.639990
Fangjun Jiang
il 13 Set 2011
If I just change the size of A, A=rand(100), the result is opposite. So, we need insights.
t1=0.039258
t2=0.036136
Teja Muppirala
il 13 Set 2011
It is probably version dependent. I use R2011b and I find that if I run your code for A = rand(1000), I get:
t1=3.190328
t2=2.453046
For A = rand(100), I get:
t1=0.040473
t2=0.030582
I couldn't tell you the reason why, but I do know that a lot of the elementary math functions have been getting much faster lately.
Jan
il 13 Set 2011
@Teja: The math functions are limited by the processor speed, if the data match into the processor cache. For large data the memory access should be the limiting factor. Therefore I'd expect your function to be much slower for RAND(1000).
@Fangjun: I get these timings on 2009a running in a single core environment: t1=6.282469, t2=5.247344.
Categorie
Scopri di più su Creating and Concatenating Matrices in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!