How can I take the last value and sum the values of a row of ones in a matrix?
4 ビュー (過去 30 日間)
古いコメントを表示
Hi!
I have the following (large) dataset
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1593176/image.jpeg)
and I would like to produce the following output
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1593181/image.jpeg)
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 件のコメント
Image Analyst
2024 年 1 月 17 日
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.
採用された回答
Sufiyan
2024 年 1 月 21 日
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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!