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

2 次查看(过去 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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by