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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by