I need help with logical indexing
조회 수: 8 (최근 30일)
이전 댓글 표시
The instructions are to "Construct an indexing array so that the statement
playerOneScores = gameScores(playerOnesEntries);
results in a row array playerOneScores with only player 1's scores."
function playerOneScores = GetPlayerScores(gameScores)
% gameScores: Array contains both player1 and player2's scores.
% Array contains 8 elements
gameScores = [playerOneEntries playerTwoEntries]
% FIXME: Construct a logic array to indicate which elements belong to player 1
playerOneEntries = [true, false, true, false, true, false, true, false];
playerTwoEntries = [false, true, false, true, false, true, false, true];
% Do not modify the following statement
playerOneScores = gameScores(playerOnesEntries);
end
댓글 수: 0
답변 (1개)
Walter Roberson
2017년 10월 9일
You have
function playerOneScores = GetPlayerScores(gameScores)
gameScores = [playerOneEntries playerTwoEntries]
This takes gameScores as input, but tries to overwrite it with [playerOneEntries playerTwoEntries] . Are playerOneEntries and playerTwoEntries functions that take no arguments, or are they shared variables? At the moment they do not appear to be defined at that point. But then you define variables with those names in the following lines.
If you had first done
playerOneEntries = [true, false, true, false, true, false, true, false];
playerTwoEntries = [false, true, false, true, false, true, false, true];
and then done
gameScores = [playerOneEntries playerTwoEntries]
then the result would have been to overwrite the input gameScores variable with a vector of 8+8 = 16 logical values, making it
[true, false, true, false, true, false, true, false, false, true, false, true, false, true, false, true]
Your line
playerOneScores = gameScores(playerOnesEntries);
would then use the 8 logical indexes in playerOneEntries to index into the 16 values of gameScores. MATLAB does define what it means to use a logical index shorter than the value being indexed into: it is defined to be as if the remaining selectors were all false, so it would be equivalent to doing
gameScores([true, false, true, false, true, false, true, false, false, false, false, false, false, false, false, false])
The result would be a logical array that, in this case, would have extracted 4 entries. Somehow I doubt that you want to be returning a logical array.
... Your code would probably be fine if you simply deleted the line
gameScores = [playerOneEntries playerTwoEntries]
댓글 수: 3
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!