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
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에 대해 자세히 알아보기

태그

질문:

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