Code optimization by avoiding loops

I have the following Data and Variables
data = 1000x2 double array containing x and y coordinates
B = 1000x1 integer array containing category values from 1 to j inclusive
A = need to create this array which contains values that are the mean of all the points for each category (x and y values to be averaged separately)
I have the following code which works as desired. I am wondering whether there is a better way of doing it without the loop,
for i = 1:j
A(i,:) = mean(data(B==i,:));
end
Thank you.

 Accepted Answer

Matt J
Matt J on 2 Dec 2017
Edited: Matt J on 2 Dec 2017
B=B(:);
N=accumaray(B,1);
A(:,1)=accumaray(B,data(:,1))./N;
A(:,2)=accumaray(B,data(:,2))./N;

6 Comments

You could also use accumarray(...,@mean) but in past Matlab versions, at least, that has been found to be slower.
I'm new to matlab and not familiar with that expression? Can you please suggest the full code out of interest? Your previous code works perfectly btw. Thanks a bunch.
Can you please suggest the full code out of interest?
A(:,1)=accumaray(B(:),data(:,1),[],@mean);
A(:,2)=accumaray(B(:),data(:,2),[],@mean);
I'm new to matlab and not familiar with that expression?
Since you're new, it will benefit you to know that you can bring up usage documentation on any command, e.g.,
>> doc accumarray
Thanks. Can the same be done when plotting the values? My current code is,
for i = 1:j
C = data(B==i,:);
plot(C(:,1),C(:,2));
end
Matt J
Matt J on 2 Dec 2017
Edited: Matt J on 3 Dec 2017
Once you read "doc accumarray", you will know ;)
A fancy trick you might be able to do is
args=[accumarray(B(:),data(:,1),[],@(q) {q}),...
accumarray(B(:),data(:,2),[],@(q) {q})].';
plot(args{:})

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 2 Dec 2017

Edited:

on 3 Dec 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!