Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

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

조회 수: 2 (최근 30일)
keyboard_cuts
keyboard_cuts 2015년 12월 10일
마감: MATLAB Answer Bot 2021년 8월 20일
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
Stephen23
Stephen23 2015년 12월 10일
편집: Stephen23 2015년 12월 10일
@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.

답변 (1개)

Nicolas Gn
Nicolas Gn 2015년 12월 10일
편집: Nicolas Gn 2015년 12월 10일
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)).

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by