Info
此问题已关闭。 请重新打开它进行编辑或回答。
how can i sum
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(3 个)
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
0 个评论
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')
0 个评论
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.)
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!