How generate an error to prevent an infinite loop in this function?

1 次查看(过去 30 天)
Hi, I'd like to know if it's possible to generate an error in this code(function) to prevent an infinite loop... I put an Initial matrix A of dimension 4x4. I want to make 8 groups by using this function (explanations below code):
function [B, idx1, idx2] = selector(A)
m=8; %number of groups
n=numel(A);
ii=0;
idx=[];
while ii<m
Permutation=randperm(n);
id=setdiff(Permutation,idx,'stable');
[ ii1,jj1]=ind2sub(size(A),id(1));
[ ii2,jj2]=ind2sub(size(A),id(2));
if or(abs(ii1-ii2)==1 & abs(jj1-jj2)==0,abs(ii1-ii2)==0 & abs(jj1-jj2)==1);
ii=ii+1;
idx=[idx id(1:2)];
B(ii,:)=[A(id(1)) A(id(2))];
end
end
disp(idx);
[idx1,idx2]=ind2sub(size(A),idx);
end
This function just returns groups (2 by 2) from elements of the matrix A. (these elements are adjacent (not diagonally) in A. And they're taken only one time) The matrix B contains these groups. (Just run the function to see) The function just run into an infinite loop when the last elements chosen in A are not adjacent and there are no other possibilities to group them. Thank You very much.
  2 个评论
Image Analyst
Image Analyst 2013-6-15
What is A? Please give code to create a sample "A" and call selector(), so we can help you.
Lorenz
Lorenz 2013-6-16
ok sorry, A is a matrix dimension 4x4, A is that kind of matrix:
A =
2 4 1 3
4 2 3 1
1 3 4 2
3 1 2 4
We just apply the function to A. Example:
EDU>> [B ,idx1,idx2]=selector(A)
B =
2 4
3 1
3 1
2 4
3 1
1 3
2 4
4 2
idx1 =
1 2 4 4 2 1 3 4 1 2 3 3 2 1 3 4
idx2 =
1 1 1 2 3 3 4 4 4 4 1 2 2 2 3 3
This is how the function works. But sometimes, it can't make all the groups (just run the code to see), and I have to restart again and again till I have my 8 groups. This is what I want to correct. Thank you.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by