سؤال

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.

هل كانت مفيدة؟

المحلول

accumarray does just that:

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

نصائح أخرى

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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top