I have a 5x6 matrix. I want to calculate sum of only those values which are consecutive nonzero along each row. How to do that? The desired result given in description box.

조회 수: 4 (최근 30일)
a = [2 3 1 4 0 0;
0 0 0 0 0 0;
0 0 1 5 7 0;
0 0 0 0 4 0;
4 5 0 0 6 8];
desired_result = [10;0;13;0;23]
desired_result = 4×1
10 0 13 0
  댓글 수: 4
Payel
Payel 2023년 6월 24일
The result of 4th row is not 4 because I want summation of only consecutive non zero values along each row.
The desired result of a should be 17
the cyclist
the cyclist 2023년 6월 24일
I believe a correct re-statement of the rule is, "Sum all non-zeros that are next to at least one other non-zero."

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2023년 6월 24일
편집: the cyclist 2023년 6월 24일
I believe this does what you want:
% Input
a = [2 3 1 4 0 0;
0 0 0 0 0 0;
0 0 1 5 7 0;
0 0 0 0 4 0;
4 5 0 0 6 8];
% Append columns of zeros at both ends, because we are going to check in
% the next line if an element is a "singleton" with zeros on both sides
b = [zeros(height(a),1) a zeros(height(a),1)];
% Identify the non-singleton value (i.e. the ones that do not have zeros on either side)
includeInSum = not((b(:,1:end-2) == 0) & (b(:,3:end)==0));
% Sum the values that should be included
result = sum(a.*includeInSum,2)
result = 5×1
10 0 13 0 23

추가 답변 (1개)

Image Analyst
Image Analyst 2023년 6월 24일
a = [2 3 1 4 0 0;
0 0 0 0 0 0;
0 0 1 5 7 0;
0 0 0 0 4 0;
4 5 0 0 6 8];
desired_result = [10;0;13;0;23]
desired_result = 5×1
10 0 13 0 23
desired_result = sum(a, 2)
desired_result = 5×1
10 0 13 4 23
To learn other fundamental concepts, invest 2 hours of your time here:
  댓글 수: 2
Payel
Payel 2023년 6월 24일
how to get the summation value of 4th row to be zero? as it is asked to find summation of only consecutive nonzero values along each row
Image Analyst
Image Analyst 2023년 6월 24일
Row 4 has one "consecutive' value, so why not sum it in? Do you want to sum in values only if the run of non-zero values is 2 or more? See @the cyclist's answer below. Is it homework? If so you can't use it.
This looks like a homework problem. If you have any questions ask your instructor or read the link below to get started:
Obviously we can't give you the full solution because you're not allowed to turn in our code as your own.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by