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

2 次查看(过去 30 天)
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.

更多回答(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