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

조회 수: 2 (최근 30일)
Sophie Culhane
Sophie Culhane 2020년 12월 16일
댓글: Ameer Hamza 2020년 12월 16일
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

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 12월 16일
편집: Ameer Hamza 2020년 12월 16일
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
Sophie Culhane
Sophie Culhane 2020년 12월 16일
Thank you for your help!
Ameer Hamza
Ameer Hamza 2020년 12월 16일
I am glad to be of help!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by