in a nested for loop, if statement: how to keep doing something until a condition is met
古いコメントを表示
Dear all,
I have a 6x6 matrix of integers. In a for loop, for each entry in the matrix I grab a 3x3 submatrix and I randomly select an entry from the entire matrix. Then I want to see if the randomly selected entry is present in the submatrix as well. If it is, the original entry is replaced by the randomly selected entry. If not, I want to randomly select another entry and compare, keep doing this until I can find a randomly selected entry that is present in my submatrix and replace the original entry with it.
How would I write it so that if the first randomly selected entry is not present, I go back to randomly select another entry and repeat this process?
So far I have:
mat=[1 2 3 4 5 2; 3 4 5 1 1 1; 1 6 5 9 9 9; 1 3 4 1 3 1; 6 6 6 6 6 6; 1 9 9 2 3 4];
for ii=1:6 for jj=1:6 % going over each entry in the matrix
for x=-1:1; for y=-1:1; mat_sub(x+2,y+2) = mat(mod(ii+x,6)+1,mod(jj+y,6)+1); end end % grabbing a 3x3 submatrix with periodic boundaries
rand_idx = 1 + fix(rand(1,1)*6); rand_idy = 1 + fix(rand(1,1)*6); % generate a randomly selected indices
% check whether the randomly selected entry is present in the submatrix, % if it is then replace the old value with the new value.
if ismember(mat(rand_idx,rand_idy),mat_sub)==1 mat(ii,jj)=mat(rand_idx,rand_idy); else rand_idx = 1 + fix(rand(1,1)*6); rand_idy = 1 + fix(rand(1,1)*6); end end end
I'd need to write something after else, but I'm not sure how I'd do this. Any help is most appreciated.
採用された回答
その他の回答 (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!