Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

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

1 vue (au cours des 30 derniers jours)
keyboard_cuts
keyboard_cuts le 10 Déc 2015
Clôturé : MATLAB Answer Bot le 20 Août 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 commentaires
Stephen23
Stephen23 le 10 Déc 2015
Modifié(e) : Stephen23 le 10 Déc 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.

Réponses (1)

Nicolas Gn
Nicolas Gn le 10 Déc 2015
Modifié(e) : Nicolas Gn le 10 Déc 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)).

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by