Length command giving rise to array indices must be positive integers or logical values error
16 views (last 30 days)
Show older comments
Roderick
on 31 Oct 2024 at 17:38
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?
0 Comments
Accepted Answer
Walter Roberson
on 31 Oct 2024 at 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.
0 Comments
More Answers (1)
Voss
on 31 Oct 2024 at 17:53
Edited: Voss
on 31 Oct 2024 at 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).
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!