Question

Is there a way to vectorize the following loop in MATLAB?

for j = 1:length(cursor_bin)
    cursor_bin(j) = mean(cursor(bin == j));
end

cursor_bin, cursor, and bin are all vectors.

Was it helpful?

Solution

accumarray does just that:

cursor_bin = accumarray(bin(:), cursor(:), [], @mean);

OTHER TIPS

bsxfun approach for non-zero cursor arrays -

t1 = bsxfun(@eq,bin(:),1:numel(cursor_bin))
t2 = bsxfun(@times,t1,cursor(:))
t2(t2==0)=NaN
cursor_bin = nanmean(t2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top