Sort and accumulate data in a matrix
1 view (last 30 days)
Show older comments
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 Comments
Walter Roberson
on 27 Jan 2020
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]), :) = [];
Answers (1)
Stephan
on 27 Jan 2020
Edited: Stephan
on 27 Jan 2020
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 Comments
Stephan
on 27 Jan 2020
@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.
See Also
Categories
Find more on Matrices and Arrays 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!