Sort and accumulate data in a matrix

1 次查看(过去 30 天)
Elli
Elli 2020-1-27
评论: Stephan 2020-1-27
Hi everyone,
I have written a code but it's to messy, I'm sure one could sum it up.
This is the data I have:
data= [0 -50
-10 -50
-10 -50
0 -40
-10 -40
10 -40
10 -30
-10 -30
0 -30
... and so on till +50.
The output I want should be seperated for the three values in the first column so that the output for 0, 10 and -10 should separatley look like this:
[ -50 0
-40 0
-30 0
-20 1
-10 1
0 2
10 6
20 6
30 6
40 6
50 6 ]
so thst the first column lists every value once and the second column the amount of occurance of ones for that specific value.
My code:
%%0 (delete others)
data(find(data(:,1)==10),:)=[]
data(find(data(:,1)==-10),:)=[]
%% 10 (delete others)
data(find(data(:,1)==0),:)=[]
data(find(data(:,1)==-10),:)=[]
%% -10 (delete others)
data(find(data(:,1)==10),:)=[]
data(find(data(:,1)==0),:)=[]
And then for every data (unfortenately) separately the following:
for i = size(data)
data1=sum(data(1:3,2))
data2=sum(data(4:6,2))
data3=sum(data(7:9,2))
data4=sum(data(10:12,2))
...
end
comp_data=[data1, data2, data3, data4]'
test_angle=unique(data(:,2));
dataAll=horzcat( test_angle,comp_data)
I am pretty sure one could sum it up by different for/if loops so that I don't have to run it for 0, 10 and -10 separately and independetly from fixed row values.
Thanks a lot!!!
  2 个评论
Walter Roberson
Walter Roberson 2020-1-27
data(find(data(:,1)==10),:)=[]
data(find(data(:,1)==-10),:)=[]
%% 10 (delete others)
data(find(data(:,1)==0),:)=[]
data(find(data(:,1)==-10),:)=[]
?? The -10 are already gone -- you deleted them in the second statement.
Have you considered
data(ismember(data(:,1), [-10 0 10]), :) = [];
Elli
Elli 2020-1-27
Your suggestion leads leads to an empty struct!
And you are right, I am sorry, it was a typo.
%% 10 (delete others)
data(find(data(:,1)==0),:)=[]
data(find(data(:,1)==-10),:)=[]

请先登录,再进行评论。

回答(1 个)

Stephan
Stephan 2020-1-27
编辑:Stephan 2020-1-27
Here is an example:
A = [-10 0 10 10 20 -20 30 -30 40 -50 50 -40 -10 0 0 10 20 -20 30 -30 40 -50 50 -40 40 40 40];
groups = findgroups(A);
occurences = splitapply(@numel,A,groups);
result = [unique(A); occurences].'
  3 个评论
Elli
Elli 2020-1-27
Hi Stephan, thank you!
This counts the occurance of the values in the first column (A), not the corresponding values in the second row!
Stephan
Stephan 2020-1-27
@Elli This was just to give you a direction how to improveyour approach. Together with the commentfrom Guillaume you should be able to do this in a proper way.
@Guillaume Thank you for the hint, again a nice new fact i did not notice so far.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by