How to replace specific values with 0's
2 次查看(过去 30 天)
显示 更早的评论
Dear all,
I have a 1435x205 matrix and I want to obtain the sum of a specific set of cells. In this case it is from the 146th to the 150th column and from the 316th to 351th row, which gives me a 35x5.
My first thought was to replace all values in the matrix except the specific values I just pointed out with 0's and then use a summation vector. Does anyone have an idea on how to do this? Preferably a generalized method.
For example assume that I have a 5x5 matrix
A = magic(5)
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
And let's assume I want the values in the 2nd and 3rd row and the second and third row to be replaced by 0. Which gives me this result:
A =
0 0 0 0 0
0 5 7 0 0
0 6 13 0 0
0 0 0 0 0
0 0 0 0 0
Is there a simple command for this?
Finally, I want to sum these values (the total is 31):
sum=ones(1,5)*A*ones(5,1)
sum =
31
If anyone knows, is there a more succinct way to pick out which elements from a matrix matlabs sums using summation vectors?
Best wishes.
2 个评论
Ty Watkins
2022-1-12
The easiest way I can think of would be to just use the built in sum function and use row/column subscript ranges.
Also, you don't really want to store your answer into the variable named 'sum' as this will prevent you from using the built in function 'sum' until you clear your workspace
s = sum(A(2:3,2:3),'all') % A(row_range,column_range)
You have to provide the optional argument 'all', otherwise it will return a row vecotr containt the sum of each column
采纳的回答
Voss
2022-1-12
A = rand(1435,205);
B = A(316:351,146:150) % 36-by-5
sum(B(:))
or:
sum(sum(A(316:351,146:150)))
or:
sum(A(316:351,146:150),'all')
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!