I need help with logical indexing
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Walter Roberson
am 9 Okt. 2017
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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!