Correct error in logical indexing

1 回表示 (過去 30 日間)
Morten Jørgensen
Morten Jørgensen 2019 年 4 月 23 日
編集済み: Guillaume 2019 年 4 月 23 日
Hi, I can't figure out why i get the wrong result in this loop
I now when k=3 it should be 1, but I get a 0.
it gives me a array only containing of 0
thanks a lot for your help.
for k = length(PassCoord)
X(k,1) = mBall(PassCoord(k,1)) > mBall(PassCoord(k,2))
end

採用された回答

Alex Mcaulley
Alex Mcaulley 2019 年 4 月 23 日
Your loop only runs for k = length(PassCoord), you need to put the limits of k (1:length(PassCoord)):
for k = 1:length(PassCoord)
X(k,1) = mBall(PassCoord(k,1)) > mBall(PassCoord(k,2))
end
  2 件のコメント
Morten Jørgensen
Morten Jørgensen 2019 年 4 月 23 日
arh, thanks a lot :)
Guillaume
Guillaume 2019 年 4 月 23 日
編集済み: Guillaume 2019 年 4 月 23 日
DO not use length on a matrix. See explanation in my answer.
And also, do not use the loop anyway, it's long-winded and unnecessary.

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

その他の回答 (1 件)

Guillaume
Guillaume 2019 年 4 月 23 日
  • You use length on a matrix. If your matrix happens to only have one row, your code will error since length will return the number of columns in that case. Here length means the number of rows, so use size(PassCoord, 1) to explicitly request the number of rows.
  • What's the point of the loop> the whole code is equivalent to:
X = mBall(PassCoord(:, 1)) > mBall(PassCoord(:, 2));
As for what you don't get the result you expect, we can't tell without knowing what's in mBall and PassCoord. Either the code you wrote doesn't do what you meant it to do or the inputs are different from what you think. So explain and attach the two variables in a mat file.

カテゴリ

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