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