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

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

Walter Roberson
Walter Roberson il 18 Gen 2021
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 Commento
Melvin Babel
Melvin Babel il 18 Gen 2021
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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by