How can I take the last value and sum the values of a row of ones in a matrix?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Francesco
am 17 Jan. 2024
Kommentiert: Francesco
am 22 Jan. 2024
Hi!
I have the following (large) dataset
figure 1
and I would like to produce the following output
figure 2
In practice, when there are more than 1 zeros in column 1 (see rows 17:19, figure 1) I would like to replace in row 17 (see figure 2)
- the value of 0 in row 19 and column 1 of figure 1
- the value of 250 in row 20 and column 2 of figure 1
- the sum of the values in form row 17 to row 19 and column 3 of figure 1
- the value of -1 in row 19 and column 4 of figure 1
and I want to do this every time when there are more than 1 consecutive zeros in column 1.
To clarify, I would replace row 17 of figure 1 a row composed by the following values: [0 (row 19, col 1); 250 (row 20, col 2); the sum of the values from row 17 to row 19 of col 3; -1 (row 19, col 4)] and repeat this every time there are more than one zeros in column 1.
Thanks in advance for the help!
3 Kommentare
Image Analyst
am 17 Jan. 2024
What are you doing with row 20??? It lookos like you just want to replace row 17 with things and then delete rows 18 and 19. Is that correct?
If you have the Image Processing Toolbox you can easily find the rows with 2 or more consecutive zeros in column 1 using bwlabel and regionprops.
Akzeptierte Antwort
Sufiyan
am 21 Jan. 2024
data = rand(11, 3);
data(:, 1) = [1; 0; 0; 0; 2; 0; 0; 0; 0; 3; 0];
sampleTable = table(data(:, 1), data(:, 2), data(:, 3), 'VariableNames', {'Column1', 'Column2', 'Column3'})
consecutiveZeros = diff([0; sampleTable.Column1 == 0; 0]);
startIndices = find(consecutiveZeros == 1)
endIndices = find(consecutiveZeros == -1) - 1
Now you know the start and end indices, you can do any operations (like sum of col 3 from starting index to ending index) and modify the values and at the end delete the useless rows.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices 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!