How to average certain elements in a matrix using for loop.

4 ビュー (過去 30 日間)
jack
jack 2014 年 3 月 3 日
コメント済み: Azzi Abdelmalek 2014 年 3 月 3 日
Hello,
I am trying to operate on a matrix that has the following columns:
M=[x_coordinates y_coordinates ID] I would like to find the average x and y coordinates for same ID, in other words to group all the points that has the same ID. Can you please advice me on how to do it with Matlab.
Best regards, Jack

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 3 月 3 日
A=[ 1 2 10;5 8 10;4 3 20]
c1=A(:,1);
c2=A(:,2);
[ii,jj,kk]=unique(A(:,3));
cc1=[ii accumarray(kk,c1,[],@mean)]
cc2=[ii accumarray(kk,c2,[],@mean)]
  2 件のコメント
jack
jack 2014 年 3 月 3 日
Thank you so much, this worked great. Is it possible to use a customized function instead of mean? For example I might need to use a weighted mean by using the associated elements in another column of the matrix, for instance intensity if M=[x_coordinates y_coordinates intensity ID].
thanks.
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 3 月 3 日
A=[ 1 2 10;5 8 10;4 3 20]
weight=[10;54;87]
c1=A(:,1);
[ii,jj,kk]=unique(A(:,3));
cc1=[ii accumarray(kk,c1.*weight,[],@mean)]

サインインしてコメントする。

その他の回答 (2 件)

Sean de Wolski
Sean de Wolski 2014 年 3 月 3 日
doc accumarray
And an example:
%%sample data
n = 50;
id = randi(5,n,1);
x = rand(n,1);
y = rand(n,1);
%%engine
[uid,~,idx] = unique(id); % unique ids and the index of occurrences
mx = accumarray(id,x,[],@mean); % mean of x by id
my = accumarray(id,y,[],@mean); % mean of y by id
results = [uid mx my] % display

jack
jack 2014 年 3 月 3 日
Thank you so much for your answers! much appreciated!

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by