Matrix and element change and input help

This may be trivial but how do I get for a user input coords as a matrix, and to change the element to another number eg. a tic-tac-toe game player 1 inputs a coord to change a 0 in the matrix to a 1, and player 2 changes a 0 to -1. (player==0 when it is player 1's turn)
my code:
I=input('Number coordinate: ');
for a=1:3
for b=1:3
if B(a,b)==0
if I==1
if player==0
B(1,1)=1;
else
B(1,1)=-1;
end
elseif I==2
if player==0
B(1,2)=1;
else
B(1,2)=-1;
end
elseif I==3
if player==0
B(1,3)=1;
else
B(1,3)=-1;
end
elseif I==4
if player==0
B(2,1)=1;
else
B(2,1)=-1;
end
elseif I==5
if player==0
B(2,2)=1;
else
B(2,2)=-1;
end
elseif I==6
if player==0
B(2,3)=1;
else
B(2,3)=-1;
end
elseif I==7
if player==0
B(3,1)=1;
else
B(3,1)=-1;
end
elseif I==8
if player==0
B(3,2)=1;
else
B(3,2)=-1;
end
elseif I==9
if player==0
B(3,3)=1;
else
B(3,3)=-1;
end
end
else
disp('That is an invalid move')
end
end
end
problems with it: It will let a user set a piece on an already used part of a matrix and will always say that it is an invalid move (even if it is valid)
Could anyone help me to find a good way to do this?
-thanks, Alex

 Accepted Answer

I think you are trying to do just this:
BB = reshape(B',9,1);
I=input('number coord:');
player = 1;
BB(I) = 2*(player == 0) - 1;
B = reshape(BB,3,3)';
aren't you?

7 Comments

with
player = 0;
you'll get -1 instead of 1
This works, but I'm not sure I can understand it, could you explain it to me?
Sorry if I explained my problem as well.
I guess you are having problem in understanding this sentence:
BB(I) = 2*(player == 0) - 1;
Matlab accepts logic assignment such as above. (player == 0) will be either 1 or 0, since its a logic assignment ( watch the double = ). When player = 0, (player == 0) yields 1, and then:
BB(I) = 2*0 - 1 = -1
When player = 1, (player == 0) yields 0, and then:
BB(I) = 2*1 - 1 = 1
Thankyou very much :)
One more thing, how would you show if the input is valid or not (as an input must be a coordinate to an element with only a 0 in it).
Do you mean this?
I=input('number coord:');
if ismember(I,1:9) % this checks whether I equals 1 2 3 4 5 6 7 8 or 9
BB = reshape(B',9,1);
player = 1;
BB(I) = 2*(player == 0) - 1;
B = reshape(BB,3,3)';
end
I mean if the matrix has a -1 or a 1 in it already (this code will be in a loop), how can I find if it is in an already used spot, display that the input is invalid, and replay the input to give the user a chance to input a proper coordinate

Sign in to comment.

More Answers (1)

Categories

Find more on MATLAB 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!