Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

Can anyone see what is wrong with this code? fairly new to all this matlab!

2 visualizzazioni (ultimi 30 giorni)
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 Commenti
Stephen23
Stephen23 il 10 Dic 2015
Modificato: Stephen23 il 10 Dic 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.

Risposte (1)

Nicolas Gn
Nicolas Gn il 10 Dic 2015
Modificato: Nicolas Gn il 10 Dic 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)).

Questa domanda è chiusa.

Community Treasure Hunt

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

Start Hunting!

Translated by