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.

 采纳的回答

Matt J
Matt J 2017-12-2
编辑:Matt J 2017-12-2
B=B(:);
N=accumaray(B,1);
A(:,1)=accumaray(B,data(:,1))./N;
A(:,2)=accumaray(B,data(:,2))./N;

6 个评论

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 2017-12-2
编辑:Matt J 2017-12-3
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{:})

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by