Borrar filtros
Borrar filtros

How do I code this in a more efficient way?

1 visualización (últimos 30 días)
Mohannad Abboushi
Mohannad Abboushi el 28 de Abr. de 2016
Editada: Walter Roberson el 28 de Abr. de 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

Respuesta aceptada

Roger Stafford
Roger Stafford el 28 de Abr. de 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 comentarios
Mohannad Abboushi
Mohannad Abboushi el 28 de Abr. de 2016
I know I am asking a lot but can you explain how this works?
Roger Stafford
Roger Stafford el 28 de Abr. de 2016
Editada: Roger Stafford el 28 de Abr. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Automotive en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by