Length command giving rise to array indices must be positive integers or logical values error

조회 수: 15 (최근 30일)
Dear all
I am currently performing some nested loops, as it can be seen here
As you can see I get an error in line 150, but that happens once I have gone through that loop for dx=1 and dy=2.
I do not really understand why, after going through the for loop in line 150 for dx=1 and dy=1, I can not ask anymore for the length of Cr_atoms variable. When I get that error, Cr_atoms variable looks like
basically the same before beginning the nest for loops that begin in line 148.
Any ideas on what it is happening?

채택된 답변

Walter Roberson
Walter Roberson 2024년 10월 31일 17:46
You start out by using the length() function call. But then you assign something to length(1) . That makes length into a variable. Then the next time that what appears to be the length function call is used, instead it is a reference to the length variable.

추가 답변 (1개)

Voss
Voss 2024년 10월 31일 17:53
편집: Voss 2024년 10월 31일 17:53
The code creates a variable called "length" when this line executes:
length(1)=Cr_atoms(i,1)+dx*a; % Angstroms
Any subsequent reference to "length" will now refer to the variable "length" and not the function "length", so on the next iteration of the for dy=1:cells_b loop, when
for i=1:length(Cr_atoms(:,1))
is encountered, length(Cr_atoms(:,1)) is interpreted as a request to index the variable length with indices Cr_atoms(:,1), but since Cr_atoms(:,1) contains numbers other than positive integers, an error is thrown.
You should rename your variable "length" to something else that's not also the name of a function.
Also note that you don't need to use the "length" function at all for this, since length(Cr_atoms(:,1)) is equivalent to size(Cr_atoms,1) (assuming Cr_atoms has at least one column).

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by