How do I change one value in a matrix
4 views (last 30 days)
Show older comments
I'm trying to create a game where the matrix is going to be n x n depending on what the user inputs. The game then starts by inputting values like 5 6 to represent row column. after that i what to change that one number to a random whole number between 1 and 3 to represent if the character has hit or miss! here is my code:
name = input('Your name:', 's');
fprintf('How big is your kingdom ' , name)
b =input('Enter an integer for the size of the board):');
board = zeros(b , b);
side1 = 1;
side2 = 1;
board(side1,:) = (1:b);
board(:, side2) = (1:b);
fprintf('You have 12 knights left to defeat the 12 king');
board
move = input('Enter your next move (row space column in brackets):');
board(move) = rand(3);
I think i'm getting the multiple inputs wrong as well.... i thought by having the user input both numbers at once with brackets would work but perhaps that is wrong as well.
0 Comments
Answers (1)
Star Strider
on 30 Jul 2015
I prefer inputdlg to input, so I used it here:
movec = inputdlg('Enter your next move (row space column in brackets):');
move = str2num(movec{:});
board(move(1),move(2)) = randi(3);
I also changed your rand call to randi. Your rand(3) command would create a (3x3) matrix of random numbers on the interval [0,1] which is not what your description says you want.
It seems to work.
2 Comments
Star Strider
on 30 Jul 2015
I’ll be glad to explain it.
The inputdlg function returns a cell array of whatever inputs it receives. Since you’re only asking it for numbers here, it returns a cell string that includes the brackets and the numbers. The str2num function (along with the curly brackets {} reference to ‘movec’) then returns a (1x2) vector of double-precision numbers in the ‘move’ vector that are the coordinates you requested.
I would add a test to be sure the coordinates entered through the inputdlg call are within the address range of the matrix, and then continue looping until a correct set of coordinates are entered. (A while loop would probably be the best way of doing this.)
I would also use inputdlg for ‘name’. That code would become:
namec = inputdlg('Your name: ');
name = namec{:};
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!