Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to find elements of a given value in a matrix?
Date: Tue, 30 Dec 2008 14:23:02 +0000 (UTC)
Organization: Bedford Institute of Oceanography
Lines: 89
Message-ID: <gjdas6$56h$1@fred.mathworks.com>
References: <16525645.1230231468100.JavaMail.jakarta@nitrogen.mathforum.org> <bOe6l.26641$wV2.14471@newsfe07.iad>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1230646982 5329 172.30.248.37 (30 Dec 2008 14:23:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 30 Dec 2008 14:23:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1149396
Xref: news.mathworks.com comp.soft-sys.matlab:509218


Walter Roberson <roberson@hushmail.com> wrote in message <bOe6l.26641$wV2.14471@newsfe07.iad>...

> An alternative is:
> sum(A(:)==1) / numels(A)
> which should be faster than find()

I decided to verify this statement by means of this fragment:

clear
A=[1 2 3; 1 2 3; 1 2 3];

tic
for i = 1:1e5
    sum(A(:)==1) / numel(A); 
end
Walter_time = toc;

tic
for i = 1:1e5
    numel(find(A==1))/numel(A);
end
Nasser_time = toc;

Walter_time > Nasser_time

ans =

     1

I was about to write: No Walter, your method takes more time... But then I just swapped the two loops:

clear
A=[1 2 3; 1 2 3; 1 2 3];

tic
for i = 1:1e5
    numel(find(A==1))/numel(A);
end
Nasser_time = toc;

tic
for i = 1:1e5
    sum(A(:)==1) / numel(A); 
end
Walter_time = toc;

Walter_time > Nasser_time

ans =

     0
-------------
OK, I thought, I will do it another way:

clear
A=[1 2 3; 1 2 3; 1 2 3];
for i = 1:1000
    tic, sum(A(:)==1) / numel(A); 
    Walter_time = toc; 
    tic, numel(find(A==1))/numel(A);
    Nasser_time = toc; 
    d(i) = Walter_time > Nasser_time;
end
sum(d==1)/1000

ans =

    0.9690

This means that in 96.7% of single passes of the loop Walter's method is slower. But then again, I swapped the lines:

>> clear
A=[1 2 3; 1 2 3; 1 2 3];
for i = 1:1000
    tic, numel(find(A==1))/numel(A);
    Nasser_time = toc; 
    tic, sum(A(:)==1) / numel(A); 
    Walter_time = toc; 
    d(i) = Walter_time > Nasser_time;
end
sum(d==1)/1000

ans =

    0.0120

The result is reverse. It turns out that whichever fragment is executed first, it takes more time. Why is that? How can you really know which method is faster?