### Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

## Trying to randomly place "ships" on a matrix for a game of battleship, running a loop to stop ships from overlapping but it continually tells me "index exceeds matrix dimensions", any pointers on how to execute the loop properly would be appreciated

Stephen

### Stephen (view profile)

さんによって質問されました 2014 年 12 月 1 日

### Star Strider (view profile)

さんによって 編集されました 2014 年 12 月 1 日
function M = AddShip( Matrix, length1)
M=Matrix;
%SHIP1--CRUISER(22)
loop_on=0;
while loop_on==0
%%%generate randomn number, gives either vert or horiz direction%%%
direction=rand(1);
if direction <=0.5
direction='vertical';
elseif direction>0.5
direction='horizontal';
end
%%%Generate randomn starting point for SHIP1-Destroyer(22)%%%
StartRow1=randi(10);
StartCol1=randi(10);
%%%if the sum of the numbers on the matrix is greater than 0 there is
%%%already a ship there, so code must run again until a suitable place is
%%%found %%%
if strcmp(direction,'vertical')==1 && sum(M( StartRow1, StartCol1:StartCol1+1 ))>0
elseif strcmp(direction,'horizontal')==1 && sum(M( StartRow1:StartRow1+1, StartCol1))>0
loop_on=0;
else loop_on=1;
end
while loop_on==1
if strcmp(direction,'vertical')==1 %if vertical add to the column
M( StartRow1, StartCol1:StartCol1+1 )=22;
elseif strcmp(direction,'horizontal')==1 %if horizontal add to the row
M( StartRow1:StartRow1+1, StartCol1)=22;
end
end
end
%%%repeat for the other 4 ships%%%

#### 0 件のコメント

サインイン to comment.

Translated by