Re: vectorize



In article <ef40a9e.-1@xxxxxxxxxxxxxxxxxxxxxxx>, jim <no@xxxxxxxxxx> wrote:

Hello,

Can anyone help vecotrize the following code please as the loop takes
extremely long to perform.

e = [1 1 1 2 2 2 2 2 3 3 3 3 3 ....etc.... ]
max(e) typically is around 50e3
a = [1 0 0 0 1 0 1 0 0 0 1 0 0....etc]

basically, I would like to find where the "1" occurs in a with repect
to the initial values of 1 ,2 ,3 etc... in e.

for i = 1:max(e)
p = find(e == i);
pp = a(p);
tt = find(pp >0);
s(1:length(tt),i) = tt;
end

answer in this case is
s = [1 2 3; 0 4 0];

thanks very much.
jim
----------------------------------
I have some questions. I presume from your for-loop code that all
elements of e are positive integers. The questions are: 1) Are you
assuming that e is already in sorted order, as in your example? 2) Are
any integers missing in e between 1 and max(e)? 3) If so or if there are
some with no matching 1's in a, do you want the corresponding columns to
be present in s and consist of all zeros, (as would occur with your
for-loop?)

I believe your code is slow because for each pass through the loop, you
have to do a scan of the entire length of e with 'find(e==i)'. Also the
fact that s has not been alloted before entering the loop causes a
slowdown as it is augmented step-by-step throughout the loop.

Depending on your answers to the above questions, there is a vectorized
way of determining the maximum length of columns needed in s, and just
possibly a way of vectorizing the entire process. I do wonder, though,
why you aren't making s a cell array which would permit variable length
columns, rather than having the vacant spaces filled in with zeros.

Roger Stafford
.



Relevant Pages

  • Re: vectorize
    ... ellieandrogerxyzzy@xxxxxxxxxxxxxxxxxxxxxx (Roger Stafford) wrote: ... I believe your code is slow because for each pass through the loop, ... possibly a way of vectorizing the entire process. ... positive integers and all like numbers are grouped together, ...
    (comp.soft-sys.matlab)
  • Re: Simple newbie question
    ... > The problem is that the loop stops at the first line with zeros and it ... > the loop). ... The loop will assign the first element of lista to line, then the second, ... the second element now becomes the first element, ...
    (comp.lang.python)
  • Re: Null object = Zero
    ... >It's obviously impossible to initialize an array by zeros ... >without a loop. ... Au contraire. ...
    (comp.lang.postscript)
  • Re: speeding up: min(A(A>0))
    ... I have a while minA<threshold loop and inside I minA is ... The number of zeros is updated in the ... the specifics depend on your algorithm. ...
    (comp.soft-sys.matlab)
  • Re: speeding up: min(A(A>0))
    ... I have a while minA<threshold loop and inside I minA is ... The number of zeros is updated in the ... which is about 50% of the total running time of my ...
    (comp.soft-sys.matlab)