필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

how can i sum

조회 수: 2 (최근 30일)
Davide Conti
Davide Conti 2019년 11월 5일
마감: MATLAB Answer Bot 2021년 8월 20일
Easy examples:
A = [1 2 3 0 -1 ; -1 -1 1 3 4 ; 2 0 1 -1 -1; etc]
For each rows, how can I sum the numbers other than -1?
So, the result for the 1st row must be 6, for the 2nd = 8, foe the 3rd =3, etc

답변 (3개)

ME
ME 2019년 11월 5일
편집: ME 2019년 11월 5일
You can make a simpler solution by just doing:
A(A<0)=0;
sum(A')
If you want to retain the original A matrix then create a copy first and the swap A to B in the above code segment, e.g.
B=A;
B(B<0)=0;
sum(B')
You can always clear B using
clear vars B
if you want to remove it from your workspace/system memory

Olawale Akinwale
Olawale Akinwale 2019년 11월 5일
I don't know that there is any easy way to do it with a one'liner... You may have to write a simple script to eliminate the -1's from the A matrix and then do the sums. For example,
A = [1 2 3 0 -1 ; -1 -1 1 3 4 ; 2 0 1 -1 -1];
Amod = A;
for i = 1:size(A,1)
for j = 1:size(A,2)
if A(i,j) == -1
Amod(i,j) = 0;
else
Amod(i,j) = A(i,j);
end
end
end
sum(Amod')

Steven Lord
Steven Lord 2019년 11월 5일
Are the -1 values just indicators that there is data missing? If so, I'd replace them with NaN values and call sum with the 'omitnan' parameter. You can replace them with NaN in several different ways. Let's take your sample data:
A = [1 2 3 0 -1 ; -1 -1 1 3 4 ; 2 0 1 -1 -1]
If you have one value that needs to be replaced, using logical indexing is easy. I'm going to make a copy of A for each of these examples so you can compare the original and modified arrays, but in your real application you may be able to change A in place.
A1 = A;
A1(A1 == -1) = NaN;
disp(A1)
S1 = sum(A1, 2, 'omitnan')
If you have multiple values you want to replace by NaN consider using standardizeMissing. For this example, I'm going to replace both -1 and 0 with NaN.
A2 = A;
A2 = standardizeMissing(A2, [0 -1]);
disp(A2)
S2 = sum(A2, 2, 'omitnan')
Once you've replaced the -1 values by NaN, other tools can treat the NaN values as missing data and handle them appropriately. As examples there are preprocessing functions that can detect, remove, or replace missing data and many of the descriptive statistics functions can handle them like sum and prod do (with 'omitnan' or 'includenan' options.)

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by