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

4 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Dyuman Joshi
Dyuman Joshi am 31 Mär. 2023
Bearbeitet: Dyuman Joshi am 31 Mär. 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
in2 = 8×1
0.5000 0.9000 1.1000 0.1000 0.3000 0.7000 0.6000 0.8000

Weitere Antworten (0)

Kategorien

Mehr zu Modeling finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by