Why do I get the Error: Array indices must be positive integers or logical values.

1 回表示 (過去 30 日間)
Xtsparse = zeros(size(Xt));
l=0.;
help = size(Xt)*keep;
rounded = round(help);
while l<rounded
Xtsparse(l)=max(abs(Xt));
while r<size(Xt)
if(Xt(r)==max(abs(Xt)))
Xt(r)=0;
end
end
end
when using this Code and try it to Run i always get the Error "Array indices must be positive integers or logical values." in line "Xtsparse(l)=max(abs(Xt));"
Does anyone know, why this Error occurs?

採用された回答

Walter Roberson
Walter Roberson 2021 年 1 月 18 日
l starts at as 0. (notice you even coded it as being floating point rather than integer!)
The assignment to help does not change l.
The assignment to rounded does not change l.
Testing l<rounded does not change l .
So when we get to
Xtsparse(l)=max(abs(Xt));
then l is still 0. and in MATLAB it is not valid to index at 0 in the Xtsparse(l) assignment statement.
Your outer while loop does not change l or rounded so if the assignment had not crashed, then the outer while loop would be an infinite loop. Your inner while loop does not change r or the size of Xt, so if it starts executing it will be an infinite loop as well.
size(Xt) is always going to return a vector of minimum length 2, so when you take size(Xt)*keep you are going to get out a vector, so help will be a vector, so rounded will be a vector. When you test l<rounded you are making a vector test; MATLAB considers vector tests true only if all parts of them are true, equivalent to while all(l<rounded, 'all') . If at some point l becomes greater than one of the elements of rounded but not greater than another element, then the while loop would consider the condition to be false, and would stop.
You encounter a similar problem with the test while r<size(Xt) which again is a vector test because size() is always a vector of minimum length 2.
If you want to test a particular dimension then provide the dimension number to size(), such as size(Xt,1)
  1 件のコメント
Melvin Babel
Melvin Babel 2021 年 1 月 18 日
Thank you fopr your Answer, I forgot that this could also be a problem and that solved it. I thought my failure was, that it would try to use a Float on an int.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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