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?
0 个评论
采纳的回答
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.
0 个评论
更多回答(1 个)
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).
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!