tags:

views:

82

answers:

1

In MATLAB, the first set of loops below accounts for duplicates, but the second set of loops (using PARFOR) does not. They overwrite the previous value. How do we fix that?

For loop:

for d = 1:length(set),
  for k = 1:length(dset),
    if strcmp(pset(k),set(d)),
      t(h,p) = dset(k);
      h = h+1;
    end
  end
end

PARFOR loop:

parfor d = 1:length(set),
  for k = 1:length(dset),
    if strcmp(pset(k),set(d)),
      t(d) = dset(k);
    end
  end
end
+2  A: 

A few points...

  1. Typos: Are you certain you should be using the variable pset, or did you mean to use dset? Also, there is an undefined variable p in the first set of loops. Should the code in the first set of loops read the following?:

    t(h) = dset(k);
    h = h+1;
    
  2. You are not doing the same thing within each set of loops. Have you tried replacing the line:

    t(d) = dset(k);
    

    with the two lines I wrote above?

  3. I can't help but notice that each of these sets of loops can be replaced with a vectorized solution, using the ISMEMBER function. Based on your code above, I believe this should accomplish the same thing:

    t = dset(ismember(pset,set));
    

    or, if pset should actually be dset:

    t = dset(ismember(dset,set));
    

    Also, it isn't a good idea to name one of your variables set, since there is a built-in function already called that: SET.

gnovice

related questions