Info
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
Can anyone see what is wrong with this code? fairly new to all this matlab!
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
This my code for placing my battleships on the board, however when i run the programme mikasa works perfectly, then yamato is issued a random space however it only occupies two index on the board as opposed to three which it should? battleships_board = zeros(10,10); ive tried adding another random number however this just adds another dimension to the battleships_board, one that cannot be accessed by the matrix, anyone got idea idea why this is happening?
mikasa=[44 44];
yamato=[55 55 55];
for k=2
while 1 %Infinite loop; exits internally
pos = [randi(10) randi(10)];
if ~battleships_board(pos(1),pos(2)) %Is the location equal to
zero?
battleships_board(pos(1): pos(1)+1,pos(2)) = mikasa(k)
break
end
end
end
for k=3
while 1 %Infinite loop; exits internally
pos = [randi(10) randi(10)];
if ~battleships_board(pos(1),pos(2)) %Is the location equal to zero?
battleships_board(pos(1): pos(1)+1,pos(2)) = yamato(k)
break
end
end
end
2 comentarios
Respuestas (1)
Nicolas Gn
el 10 de Dic. de 2015
Editada: Nicolas Gn
el 10 de Dic. de 2015
Suppose that
yamato = [50 51 55];
Then when you write
battleships_board(pos(1): pos(1)+1,pos(2)) = yamato(k);
you will always assign (when the if condition is met) the value of yamato(3) (i.e. 55) to your board matrix at the positions (x,y) and (x+1,y). This is why you never get a third index.
You should write something like
battleships_board(pos(1):pos(1)+2,pos(2)) = yamato;
if you know that your ship is of length 3.
Also, you need to change your if condition (or add other conditions) such that it checks that your ship does not extend beyond dimension 10 (e.g. if you place it at position (9,9) it will extend to (11,9)).
0 comentarios
La pregunta está cerrada.
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!