How to replace specific values with 0's

3 views (last 30 days)
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 Comments
Ty Watkins
Ty Watkins on 12 Jan 2022
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

Sign in to comment.

Accepted Answer

Voss
Voss on 12 Jan 2022
A = rand(1435,205);
B = A(316:351,146:150) % 36-by-5
B = 36×5
0.0163 0.4406 0.9334 0.1858 0.1728 0.8915 0.0598 0.1625 0.4066 0.4813 0.2911 0.1403 0.6256 0.1844 0.0240 0.0914 0.8053 0.6554 0.6968 0.0514 0.7454 0.1218 0.6555 0.2145 0.0959 0.8615 0.8129 0.0892 0.5833 0.9865 0.5319 0.3094 0.7677 0.6644 0.7049 0.0716 0.0799 0.3528 0.8356 0.4728 0.5115 0.1830 0.8823 0.2619 0.9479 0.6841 0.0168 0.4885 0.6340 0.3808
sum(B(:))
ans = 85.1768
or:
sum(sum(A(316:351,146:150)))
ans = 85.1768
or:
sum(A(316:351,146:150),'all')
ans = 85.1768

More Answers (1)

Hylke Dijkstra
Hylke Dijkstra on 16 Jan 2022
Thanks!

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!