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 日

0 投票

B=B(:);
N=accumaray(B,1);
A(:,1)=accumaray(B,data(:,1))./N;
A(:,2)=accumaray(B,data(:,2))./N;

6 件のコメント

Matt J
Matt J 2017 年 12 月 2 日
You could also use accumarray(...,@mean) but in past Matlab versions, at least, that has been found to be slower.
Alex
Alex 2017 年 12 月 2 日
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.
Matt J
Matt J 2017 年 12 月 2 日
編集済み: Matt J 2017 年 12 月 2 日
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
Alex
Alex 2017 年 12 月 2 日
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 ;)
Matt J
Matt J 2017 年 12 月 2 日
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 ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2017 年 12 月 2 日

編集済み:

2017 年 12 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by