function locs = getLocationClosest(topN, assignedCats, categories, ...
  trainAllPos, numToConsider)
% Gets the locations of the nearest assigned category bounding box for each
% cluster.
locs = cell(length(topN), 1);
for i = 1 : length(topN)
  imgIds = topN{i}.imgIds;
  toSel = min(length(imgIds), numToConsider);
  imgIds = imgIds(1:toSel);
  hasCategory = false(size(imgIds));
  for j = 1 : length(imgIds)
    objNames = {trainAllPos(imgIds(j)).annotation.object.name};
    hasCategory(j) = ismember(categories{assignedCats(i)}, objNames);
  end
  selected = find(hasCategory);
  catLoc = getRelativeCategoryLocationForPatch(topN{i}.meta(selected), ...
    trainAllPos(imgIds(selected)), true, categories{assignedCats(i)});
  locs{i} = cell2mat(catLoc);
end
end

function locs = getRelativeCategoryLocationForPatch(patches, anno, ...
  selectClosest, primaryCat)
pedPos = cell(size(anno));
homeImgs = '';
for i = 1 : length(anno)
  pedPos{i} = convertDataSun09ToPedro(primaryCat, anno(i), [], ...
    false, homeImgs);
end

locs = cell(length(patches), 1);
for i = 1 : length(patches)
  xyLoc = zeros(length(pedPos{i}), 2);
  scLoc = zeros(length(pedPos{i}), 1);
  aspLoc = zeros(length(pedPos{i}), 1);
  
  [cx cy] = getPatchCenter(patches(i));
  cVertExt = getPatchVerticalExtent(patches(i));
  imgPedPos = pedPos{i};
  for m = 1 : length(imgPedPos)
    [px py] = getPatchCenter(imgPedPos(m));
    pVertExt = getPatchVerticalExtent(imgPedPos(m));
    xyLoc(m, :) = ([px py] - [cx cy]) / cVertExt;
    scLoc(m) = pVertExt / cVertExt;
    aspLoc(m) = getPatchAspectRatio(imgPedPos(m));
  end
  
  if selectClosest
    dists = pdist2(xyLoc, [0 0], 'euclidean');
    [unused, ind] = min(dists);
    locs{i} = [xyLoc(ind, :) scLoc(ind) aspLoc(ind)];
  else
    locs{i} = [xyLoc scLoc aspLoc];
  end
end
end
