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

3 vues (au cours des 30 derniers jours)
Sophie Culhane
Sophie Culhane le 16 Déc 2020
Commenté : Ameer Hamza le 16 Déc 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

Réponse acceptée

Ameer Hamza
Ameer Hamza le 16 Déc 2020
Modifié(e) : Ameer Hamza le 16 Déc 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 commentaires
Sophie Culhane
Sophie Culhane le 16 Déc 2020
Thank you for your help!
Ameer Hamza
Ameer Hamza le 16 Déc 2020
I am glad to be of help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by