How to find duplicated values and calculate the mean of them?

2 views (last 30 days)
I have a data set of points that consist latitudes, longitudes and respectively velocities. I need to find the same points (same latitudes and longitudes), but need to take the average of their velocities. So my new data set will consist no duplicates but instead averaged velocity values of those duplicants. But I dont know how can I find the duplicated values and how to merge them with non duplicated ones.
You can find my code and data here;
clear all;
a = load('all_velocities.txt');
A = [a(:,1) a(:,2)]; % latitude and longitudes
k=1;
for i = 1:length(A)
[U, ia] = unique(A, 'rows'); %unique values
DATA(k,:) = [U(ia,1) U(ia,2) a(ia,3) a(ia,4)]; % new data set with unique lat and lon and their velocities
k=k+1;
end
So far I ended up with this error message:
Index in position 1 exceeds array bounds (must not exceed 385).
Error in duplicate (line 9)
DATA(k,:) = [U(ia,1) U(ia,2) a(ia,3) a(ia,4)];
Also I need to calculate the average velocity of those duplicated ones and merge them with data.

Answers (1)

Stephen23
Stephen23 on 21 Feb 2020
Edited: Stephen23 on 21 Feb 2020
Here is one solution:
>> M = dlmread('all_velocities.txt');
>> [~,~,X] = unique(M(:,1:2),'rows');
>> F = @(x) mean(M(x,:),1);
>> Data = arrayfun(F,1:max(X),'UniformOutput',false));
>> Data = vertcat(Data{:});
Another option would be to use a table:
  3 Comments
Stephen23
Stephen23 on 21 Feb 2020
@Sevil Cansu Yildirim: your comment shows some unrelated code which uses different data files to the one you provided in your question. I have no idea how your comment relates to your question or to my answer.
Sevil Cansu Yildirim
Sevil Cansu Yildirim on 24 Feb 2020
here i load the data you reduced for me (duplicates are averaged)
a = load('data.txt');
this code is just something i use for plotting the data. when i plot matrix a, it is the arrows at the figure in the end. and you can see duplicated arrows.

Sign in to comment.

Categories

Find more on Specifying Target for Graphics Output in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!