Repeating If statement after variable change
9 views (last 30 days)
Show older comments
Melissa Rosie
on 6 Apr 2017
Commented: Joseph Cheng
on 6 Apr 2017
Hello! I have a question about the usage of 'return' and/or 'repeat.' I have an if statement that takes in an m x 1 vector (lets call it SS) and outputs a common number vector between specified arrays above it in the function. However, if the length of the common number vector is greater than one, then I would change the SS input and repeat the first if statement. How would I do this without making a nested or subfunction? Thank you!
%A simplified example:
A = [1 2 3 4];
B = [1 2 6];
C = [1 7];
if SS(1)==1;
commonnums = intersect(A,B); %commonnums would be [1 2]
if length(commonnums)>1;
SS = SS + 1;
%repeat first if statement with SS(1)==2;
else
commonnums = commonnums;
end
elseif SS(1)==2;
commonnums = intersect(A,C); %commonnums would now be [1]
if length(commonnums)>1;
SS = SS + 1;
%repeat first if statement with SS(1)==3;
else
commonnums = commonnums;
end
elseif SS(1)==3;
commonnums = intersect(B,C); %commonnums would be [1] also
if length(commonnums)>1;
SS = SS - 2;
%repeat first if statement with SS(1)==1;
else
commonnums = commonnums;
end
end
0 Comments
Accepted Answer
Joseph Cheng
on 6 Apr 2017
not sure what you mean by repeat first with SS(1)==# as it wouldn't do the first if statement but the lower elseif statement. if thats the case make them seperate ifs? i can't figure out what youre trying to do but a shorter way is to do something like this and then you can determine which combination you want without having to make an if statement with the specific variable hard coded in.
commonnums = [0 0];
SS = [1 2 3];
A = [1 2 3 4];
B = [1 2 6];
C = [1 7];
ABC = {A;B;C}
combos = nchoosek(1:3,2);
whichcombo = SS(1);
while length(commonnums)>1
commonnums = intersect(ABC{combos(whichcombo,1)},ABC{combos(whichcombo,2)});
if length(commonnums)>1
SS=SS+1;
whichcombo=SS(1);
else
disp('done')
end
end
2 Comments
Joseph Cheng
on 6 Apr 2017
So how are you defining the sudoku grid? there maybe a faster easier way to go through and find these items.
But either way did my thing help? I'd hate to leave you unanswered.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!