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

15 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 31 Okt. 2024 um 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.

Weitere Antworten (1)

Voss
Voss am 31 Okt. 2024 um 17:53
Bearbeitet: Voss am 31 Okt. 2024 um 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).

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by