Reputation: 343
I want to avoid using a loop to create a list of average values from a larger vector. I have the indices in the larger vector for each location in the 'average' vector, but I don't want to wrap this in a loop. Is there a cellfun() method in Matlab to expedite the process. Code and examples follow:
tVector = 10 : 15;
values = [ 10.1 10.2 10.3 11.4 11.5 11.6 11.7 12.8 12.9 13 13.1 13.2 13.3 13.3 14 14.1 14.2 ];
[ x, n ] = histc( values, tVector );
if any( x ~= 0 )
indxList = unique( n );
avgList = NaN * ones( length( indxList ), 1 );
for k = 1 : length( indxList )
theseIndxs = find( indxList( k ) == n );
avgValue = mean( values( theseIndxs ) );
avgList( indxList( k ) ) = avgValue;
end
end
The data here are for a trivial example with a small data set. But, my data have much longer lengths, so I'd like to avoid the 'for' loop with possibly the cellfun().
Upvotes: 0
Views: 40
Reputation: 112659
Use accumarray
with the @mean
function:
avgList = accumarray(n(:), values(:), [], @mean);
Upvotes: 1