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.

 Akzeptierte Antwort

Matt J
Matt J am 2 Dez. 2017
Bearbeitet: Matt J am 2 Dez. 2017

0 Stimmen

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

6 Kommentare

Matt J
Matt J am 2 Dez. 2017
You could also use accumarray(...,@mean) but in past Matlab versions, at least, that has been found to be slower.
Alex
Alex am 2 Dez. 2017
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 am 2 Dez. 2017
Bearbeitet: Matt J am 2 Dez. 2017
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 am 2 Dez. 2017
Bearbeitet: Matt J am 3 Dez. 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{:})

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 2 Dez. 2017

Bearbeitet:

am 3 Dez. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by