How to Assign a Variable Name to a Point in a Matrix

2 visualizaciones (últimos 30 días)
Sophie Culhane
Sophie Culhane el 16 de Dic. de 2020
Comentada: Ameer Hamza el 16 de Dic. de 2020
I am trying to assign variable name 'centersquare' to the center point in an NRows x NCols matrix. In my program, I had the center calculated every time I went through a for-loop and it worked. However, my professor instructed me to only calculate it once outside of the for-loop to be more efficient. I have tried various things in attempt to only calculate my centersquare once, however it does not work with my program.
Here is what I had before:
for pebbles = 1:NP
A(ceil(NRows/2),ceil(NCols/2)) = A(ceil(NRows/2),ceil(NCols/2)) + 1;
...
end
Here is what I am trying to do:
centersquare = A(ceil(NRows/2),ceil(NCols/2));
for pebbles = 1:NP
centersquare = centersquare + 1;
...
end
Can someone tell me why this isn't working? Thank you

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 16 de Dic. de 2020
Editada: Ameer Hamza el 16 de Dic. de 2020
I guess your professor asked to pre-calculate the indexes. Something like this
row = ceil(NRows/2);
col = ceil(NCols/2);
for pebbles = 1:NP
A(row,col) = A(row,col) + 1;
...
end
btw, I will be surprised if there is a significant difference. MATLAB JIT compiler is probably intelligent enough to see that the same thing is being used in each iteration. However, this is definitely more readible.
  2 comentarios
Sophie Culhane
Sophie Culhane el 16 de Dic. de 2020
Thank you for your help!
Ameer Hamza
Ameer Hamza el 16 de Dic. de 2020
I am glad to be of help!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by