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)
keyboard_cuts
keyboard_cuts el 10 de Dic. de 2015
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
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
Stephen23
Stephen23 el 10 de Dic. de 2015
Editada: Stephen23 el 10 de Dic. de 2015
@keyboard_cuts: I just formatted your code correctly for you. Next time you can do it yourself by selecting the code, and then clicking the Code {} button.

Respuestas (1)

Nicolas Gn
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)).

La pregunta está cerrada.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by