Hi, I went through the function used and found that the issue lies in the for loop of the code. The inner loop (for j = 1:9) is not necessary since each position is already uniquely defined in “ColorLocation(:, 1)”. The line “positionsnew(positions == i) = ColorLocation(i, 2)” misuses “i”, which is the loop index, not the actual position in the grid. This causes a mismatch, as positions contains grid numbers (1 to 9), not indices.
Here is a solution to map the colours correctly:
% Map coordinates to positions using formula: Position = (Row – 1) x 3 + Column
newcoords = (MrCoords(:, 1) - 1) * 3 + MrCoords(:, 2);
- MrCoords(:, 1) - 1: Subtracting 1 shifts the row index to start from 0 (0-based indexing) instead of 1 (MATLAB's 1-based indexing).
- (MrCoords(:, 1) - 1) * 3: Multiplies the adjusted row index by the number of columns (3) in the grid. This gives the starting position for that row within the linear numbering.
- + MrCoords(:, 2): Adds the column index to determine the exact position within the row. Since column numbers (1, 2, 3) directly map to positions within the row, this completes the calculation.
% Combine positions and colors
ColorLocation = [newcoords, MrC];
positions = reshape(1:9, 3, 3);
positionsnew = zeros(3, 3);
% Map colors to positionsnew
for i = 1:size(ColorLocation, 1)
[row, col] = find(positions == ColorLocation(i, 1));
positionsnew(row, col) = ColorLocation(i, 2);
end
% Display output
disp(positionsnew);
The corrected code maps colors to the exact grid positions using “positions == ColorLocation(i, 1)” inside the “find” function.
For reference, below is the link for “find” function: