help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Vectorisation


From: Andy Buckle
Subject: Re: Vectorisation
Date: Wed, 7 Jul 2010 16:50:38 +0100

On Wed, Jul 7, 2010 at 4:21 PM, gastonjulia <address@hidden> wrote:
>
> Hi there,
>
> I always knew it would come to point where my for loops are taking toooooo
> long. I know that I should use vectorised code, I do.
> But I can't figure out how I would vectorise this task:
> - I am having a 5 times 2,000,000 matrix (approximately)
> - Column 3 contains integer numbers between 1 and 20
> - For each of these numbers I want to increment the corresponding field in
> the `count' vector
>
> the solution with the for loop looks something like this
>
> octave1:>count = zeros(1,20);
> octave2:>for i = 1:length(data)
> octave3:>    count(data(i, 3))++;
> octave4:>endfor
>
> I tried using:
>
> octave1:>count = zeros(1,20);
> octave2:>count(data(:,3))++;
>
> which returns  a vector containing all `1'
>
> Is there a way to vectorise this task? Thanks!
>
> Best,
> Gaston
> --
> View this message in context: 
> http://octave.1599824.n4.nabble.com/Vectorisation-tp2281066p2281066.html
> Sent from the Octave - General mailing list archive at Nabble.com.
> _______________________________________________
> Help-octave mailing list
> address@hidden
> https://www-old.cae.wisc.edu/mailman/listinfo/help-octave
>

I only cranked n to 50000, but at that level, I get more that 100
times speedup. It still loops, but slightly smarter.

[waiting to see what better solution Jaroslav has...]
Andy

---- m script ----
n=50000;
data=ceil(rand(n,3)*20);

%slow
tic
count_slow = zeros(1,20);
for i = 1:length(data)
   count_slow(data(i, 3))++;
end
count_slow
toc

%faster
tic
count_fast = zeros(1,20);
for i = 1:20
        count_fast(i)=sum(data(:,3)==i);
end
count_fast
toc

%check they give the same answer
diff=count_fast-count_slow

--------


-- 
/* andy buckle */



reply via email to

[Prev in Thread] Current Thread [Next in Thread]