How do I code this in a more efficient way?
3 views (last 30 days)
Show older comments
Mohannad Abboushi
on 28 Apr 2016
Edited: Walter Roberson
on 28 Apr 2016
The prompt states:
Let matrix M (with R rows, C columns) represent the number of bacteria in each block of this grid. When a drop of antibiotic is delivered to a specific block at row x and column y, it kills all of the bacteria on that block and half of the bacteria in all of the neighboring blocks. After the antibiotic is delivered to the block at 2nd row and 3th column, it kills all of the 10 bacteria on that block and half of the bacteria in neighboring blocks: (2+3+13+11+8+7+6+12)/2=31; killing a total of 41 bacteria.
Write a function killbacteria(M,x,y) that returns the total number of bacteria killed.
_________________
In my function I tried creating a new matrix with the adjusted bacterial cells, but I don't know how to make it so that it avoids going into non-existent rows and columns when it is dropped in the first row/column for instance.
Here's my code so far:
function out= killbacteria(M,x,y)
out=M;
out(x,y)=0;
if x>=0 && y>=0
out(x,y-1)=1/2*M(x,y-1);
out(x,y+1)=1/2*M(x,y+1);
out(x+1,y)=1/2*M(x+1,y);
out(x-1,y)=1/2*M(x-1,y);
out(x+1,y+1)=1/2*M(x+1,y+1);
out(x-1,y-1)=1/2*M(x-1,y-1);
out(x-1,y+1)=1/2*M(x-1,y+1);
out(x+1,y-1)=1/2*M(x+1,y-1);
else
fprintf('invalid');
end
0 Comments
Accepted Answer
Roger Stafford
on 28 Apr 2016
[m,n] = size(M);
M = [zeros(1,n+2);zeros(m,1),M,zeros(m,1);zeros(1,n+2)];
out = 1/2*(M(x+1,y+1)+sum(sum(M(x:x+2,y:y+2))));
2 Comments
Roger Stafford
on 28 Apr 2016
Edited: Roger Stafford
on 28 Apr 2016
The second line of the code places a single-element-wide encirclement of zeros around the full periphery of the matrix M to give a new and larger M. This means that we don't have to make a special case of finding the neighbors for edge and corner elements in the original M - even the ones on the former edge or corner now have eight neighbors and their zero values will not affect the desired sum. The consequent shift forces us to refer to the x,y value of the former M as M(x+1,y+1) instead of M(x,y). When we sum over
M(x:x+2,y:y+2)
we are summing (times one-half) over not only the eight neighbors of M(x+1,y+1) but also over that central value itself, so that only half of the latter needs to be further added in the
1/2*M(x+1,y+1)
term. Writing 1/2*sum(sum(... yields half the sum of the column sums which gives us half the sum of all the elements in that 3x3 block: x:x+2,y:y+2.
More Answers (0)
See Also
Categories
Find more on Math Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!