This question is closed. Reopen it to edit or answer.

how can i sum

1 view (last 30 days)
Davide Conti
Davide Conti on 5 Nov 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
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

Answers (3)

ME on 5 Nov 2019
Edited: ME on 5 Nov 2019
You can make a simpler solution by just doing:
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.
You can always clear B using
clear vars B
if you want to remove it from your workspace/system memory

Olawale Akinwale
Olawale Akinwale on 5 Nov 2019
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;
Amod(i,j) = A(i,j);

Steven Lord
Steven Lord on 5 Nov 2019
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;
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]);
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