two columns of numbers with the second one sum on steps according to repeated numbers on first column

3 ビュー (過去 30 日間)
Dear experts,
I have an data file with 2 columns, data.txt --> input having thousands of lines...
In the 1st column, an integer number is increasing being repeated several times.
In the output I would like to have the sum of each next value added in the second column for each repeated number on 1st column.
input input output
---------------------
1 0.5 0.5 0.5
1 0.4 0.9 0.5 + 0.4
1 0.2 1.1 0.5 + 0.4 + 0.2
2 0.1 0.1 0.1
2 0.2 0.3 0.1 + 0.2
2 0.4 0.7 0.1 + 0.2 + 0.4
3 0.6 0.6 0.6
3 0.2 0.8 0.6 + 0.2
...................
I did something like:
load data.txt
C=(data(:,2));
[a,b] = unique(data(:,1));
[~,d] = unique(data(:,1),'last');
for i = 1 : size(a,1)
B1(i) = sum(C(b(i):d(i),1));
end
%disp(B1)
B = [B1' a]
But I got
B =
1.1000 1.0000
0.7000 2.0000
0.8000 3.0000
Any help please?
Best regards
Georgios

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 3 月 31 日
編集済み: Dyuman Joshi 2023 年 3 月 31 日
For continuous repetition -
in1 = [1;1;1;2;2;2;3;3];
in2 = [0.5;0.4;0.2;0.1;0.2;0.4;0.6;0.2];
for k=2:numel(in1)
if in1(k)==in1(k-1)
in2(k)=in2(k)+in2(k-1);
end
end
in2
in2 = 8×1
0.5000 0.9000 1.1000 0.1000 0.3000 0.7000 0.6000 0.8000
  1 件のコメント
Georgios Tsiledakis
Georgios Tsiledakis 2023 年 3 月 31 日
Thanks so much Joshi!
This is exactly what I would like to proceed.
I am really grateful for your help.
All the best
Georgios

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeModeling についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by