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

16 ビュー (過去 30 日間)
Roderick
Roderick 2024 年 10 月 31 日 17:38
編集済み: Voss 2024 年 10 月 31 日 17:53
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by