two columns of numbers with the second one sum on steps according to repeated numbers on first column
4 views (last 30 days)
Show older comments
Georgios Tsiledakis
on 31 Mar 2023
Commented: Georgios Tsiledakis
on 31 Mar 2023
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
0 Comments
Accepted Answer
Dyuman Joshi
on 31 Mar 2023
Edited: Dyuman Joshi
on 31 Mar 2023
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
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!