How to replace specific values with 0's
조회 수: 1 (최근 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에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!