我一直在学习Matlab的业余爱好。 这是我在堆栈溢出中的第二个问题。
这些天,我对Matlab的Sudoku感兴趣。 我从互联网上获取了代码,并且正在研究此代码3星期。
我想添加表示“子功能(候选)”执行次数的功能。 ->函数可用于解决方案的次数。
我曾经使用cnt = 0和cnt = cnt + 1进行计数(在if语句和while语句下) 但我意识到这段代码的结构是loop(??) *我尝试过,但尝试时将cnt重置了,我想我知道重置的原因 但我不能写代码
谢谢您的帮助
function X = s2(X)
% SUDOKU Solve Sudoku using recursive backtracking.
% sudoku(X), expects a 9-by-9 array X.
% Fill in all ?singletons?.
% C is a cell array of candidate vectors for each cell.
% s is the first cell, if any, with one candidate.
% e is the first cell, if any, with no candidates.
[C,s,e] = candidates(X);
while ~isempty(s) && isempty(e)
X(s) = C{s};
[C,s,e] = candidates(X);
end
% Return for impossible puzzles.
if ~isempty(e)
return
end
% Recursive backtracking.
if any(X(:) == 0)
Y = X;
z = find(X(:) == 0,1); % The first unfilled cell.
for r = [C{z}] % Iterate over candidates.
X = Y;
X(z) = r; % Insert a tentative value.
X = s2(X); % Recursive call.
if all(X(:) > 0) % Found a solution.
return
end
end
end
% ???????????????
function [C,s,e] = candidates(X)
C = cell(9,9);
tri = @(k) 3*ceil(k/3-1) + (1:3);
for j = 1:9
for i = 1:9
if X(i,j)==0
z = 1:9;
z(nonzeros(X(i,:))) = 0;
z(nonzeros(X(:,j))) = 0;
z(nonzeros(X(tri(i),tri(j)))) = 0;
C{i,j} = nonzeros(z)';
end
end
end
L = cellfun(@length,C); % Number of candidates.
s = find(X==0 & L==1,1);
e = find(X==0 & L==0,1);
end % candidates
end % s2
我使用了变量X
X=[4 0 0 0 2 0 0 0 0;
0 1 0 3 0 0 5 0 0;
0 0 9 0 0 8 0 6 0;
7 0 0 6 0 0 1 0 0;
0 2 0 0 0 0 0 0 9;
0 0 3 0 0 4 0 0 0;
6 0 0 7 0 0 0 2 0;
0 8 0 0 1 0 0 0 4;
0 0 0 0 0 9 3 0 0];
答案 0 :(得分:0)
您还可以使用一个持久变量,该变量应在函数的多次调用中保留其值。
例如:
function [ result ] = myfactorial( num )
% using persistent variable based on
% https://www.mathworks.com/help/matlab/ref/persistent.html
persistent numcalls;
if isempty(numcalls)
numcalls = 0;
end
numcalls = numcalls+1;
disp(strcat('numcalls is now: ', int2str(numcalls)));
% factorial function based on
% https://www.quora.com/How-can-I-create-a-factorial-function-in-MATLAB
if num > 1
result = myfactorial(num-1)*num;
else
result = 1;
end
end
现在调用该函数。
clear all;
result = myfactorial(5);
输出为:
numcalls现在是:1
numcalls现在是:2
numcalls现在是:3
numcalls现在是:4
numcalls现在是:5