Variable keeps getting error that it may not be defined in my user-built function.
53 views (last 30 days)
Show older comments
function computerColumn = computerPicksColumn(currentTokens)
% determines where the computer will drop a black token
% INPUTS:
% currentTokens: 6 by 7 matrix of integers that are 1 (yellow)
% 2 (red token) and 3 (black token)
% RETURNS:
% computerColumn: an integer between 1 and 7 that represents a column
% that is not full, i.e. a token could be dropped in it
% Initialize the column choice
computerColumn = randi(7); % Randomly chooses a column from 1 to 7
tokenValue = 3; % black tokens have a value of 3
% Check if the chosen column is valid
while true
% Check if the column is full
% Find the lowest available row in the chosen column
for row = 6:-1:1
if currentTokens(row, computerColumn) == 1
currentTokens(row, computerColumn) = tokenValue; % Place the token
return; % Exit the function after placing the token
end
end
end
end
this is the code, right above in the if statement the second line (currentTokens(r,c) = tokenValue) keeps giving an error message that variable assigned to variable might be unused.
0 Comments
Answers (1)
dpb
on 24 Oct 2024 at 14:41
Edited: dpb
on 24 Oct 2024 at 15:57
That is because it isn't used (referenced again after set).
When the function returns, the local array of that name will be lost(*); the return value is defined to be ComputerColumn and MATLAB is (by operation if not strictly by implementation) "call by value" so the array in the argument list is not updated in the caller's workspace.
You need to change the return variables to match; if the intent is to modify currentTokens in the caller, then you need to return it as well...
function [computerColumn, currentTokens] = computerPicksColumn(currentTokens)
0 Comments
See Also
Categories
Find more on Web Services in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!