random close numbers within an array
古いコメントを表示
how can i randomly extract a number and one of its four closest 'neighbours' out of an array 100x100?
5 件のコメント
Tommy
2020 年 4 月 5 日
This will give you a random element within the matrix A:
A = rand(100);
r = randi([1 size(A,1)]); % random row
c = randi([1 size(A,2)]); % random column
A(r,c)
By 'one of its four closest neighbours' do you mean any of the four adjacent elements? Or the adjacent element which is closest in value? If the former, you could always just pick
if r+1 <= size(A,1)
A(r+1,c)
else
A(r-1,c)
end
Catarina
2020 年 4 月 5 日
John D'Errico
2020 年 4 月 5 日
What if your randomly selected number lies on an edge of the array, or at a corner? Now will you randomly select from only 2 or 3 neighbors, or do something different?
Image Analyst
2020 年 4 月 5 日
How about if you make it easy and just pick a random row or column between 2 and 99.
x = 1 + randi(98, 1);
y = 1 + randi(98, 1);
Will that work for you? Then you can always be assured that a neighbor will be in the array. If not, then you've got a lot more checking to do to make sure the neighbor is not outside the array. Lots of ways but they all involve lots of if blocks or loops.
Catarina
2020 年 4 月 5 日
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!