Advertisement
Guest User

Untitled

a guest
Jan 19th, 2012
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.45 KB | None | 0 0
  1. A = double(pr);
  2. runs = 10;
  3. X = 2;
  4. Y = 4;
  5.  
  6. %--------------------------------------------------------------------------
  7. % JONAS
  8. tic
  9. for i = 1:runs    
  10.     [nRows, nCols] = size(A);
  11.     [u, v] = find(A); %# find all non-zero elements in A
  12.     %# for each row, find the highest column index with accumarray
  13.     %# and convert to linear index with sub2ind
  14.     lastIdx = sub2ind([nRows, nCols], (1:nRows)', accumarray(u, v, [nRows, 1], @max, NaN));
  15.    
  16.     goodRows1 = (A(:, 1) == X & A(lastIdx) == Y) | (A(:, 1) == Y & A(lastIdx) == X);
  17.     rows1 = A(goodRows1, :);
  18. end
  19. t1 = toc/runs
  20.  
  21. %--------------------------------------------------------------------------
  22. % BRENDAN
  23. tic
  24. for i = 1:runs
  25.     % 'a' is your array
  26.     [nx, ny] = size(A);
  27.     inds = [0:ny:ny*(nx-1)]' + sum(A ~= 0, 2);
  28.     % Needs to transpose so that the indexing reads left-to-right
  29.     aT = A';
  30.     goodRows2 = (aT(inds) == X & A(:,1) == Y) | (aT(inds) == Y & A(:,1) == X);
  31.     rows2 = A(goodRows2, :);
  32. end
  33. t2 = toc/runs
  34.  
  35. %--------------------------------------------------------------------------
  36. % OLI
  37. tic
  38. for i = 1:runs
  39.     lastNumber = sum(A.*[A(:,2:end)==0 true(size(A,1),1)], 2);
  40.     goodRows3 = find((A(:, 1) == X & lastNumber == Y) | (A(:, 1) == Y & lastNumber == X));
  41.     rows3 = A(goodRows3, :);
  42. end
  43. t3 = toc/runs
  44.  
  45. %--------------------------------------------------------------------------
  46. t1/t2
  47. t1/t3
  48. t2/t3
  49.  
  50. % CHECK EQUALITY:
  51. isequal(rows1, rows2, rows3)
  52. rows3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement