# How do I fix my Nan issue within a recursive function?

4 ビュー (過去 30 日間)
Tanner 2024 年 4 月 29 日

For my recursive function, I am trying to create a hexadoku solver. One of my variables 'mm' keeps outputting a NaN even when I try to change the NaNs into -1. I also believe that there is a base I am missing in order for this function to end. I do realize that the readmatrix function will output a NaN where there isn't an integer, but that is why there is the M(isnan(M)) = -1.
M(isnan(M)) = -1;
S = zeros(size(M));
if ~exist('S')
S = zeros(size(M));
end
FirstID = M==-1;
if isempty(FirstID)
M = S(:,:,size(S,4)+2);
else
[i,j] = ind2sub([16,16],FirstID);
for k = 1:16
ii = (ceil(i/4)-1)*4+5;
jj = (ceil(j/4)-1)*4+1;
mm = M(ii:ii+3,jj:jj+3);
mm(isnan(mm)) = -1;
if (M(i+1,:)==k)==0
if (M(:,j)==k)==0
if (mm(:)==k)==0
M(i+1,j) = k;
end
end
end
end
end
end

サインインしてコメントする。

### 回答 (1 件)

Stephen23 2024 年 4 月 29 日

Replace this (which returns logical indices):
FirstID = M==-1;
with this (which returns the linear index):
FirstID = find(M==-1,1,'first');
Note that:
• FIND can also return row&column subscript indices (i.e. you probably do not need IND2SUB).
• Using NARGIN is more efficient than EXIST.
• Your IF-statements if ...==0 will only be considered as TRUE when all elements are non-zero. This is unlikely to be the case. You probably require ANY or ALL to clarify what behavior you require, otherwise your code is very unlikely to be doing what you expect.
##### 4 件のコメント2 件の古いコメントを表示2 件の古いコメントを非表示
Tanner 2024 年 4 月 29 日
I believe I am incorrect with how the 'ii', 'jj', and 'mm' variables work. This is the script:
M(isnan(M)) = -1;
S = zeros(size(M));
if nargin == 1
S = zeros(size(M));
end
FirstID = find(M==-1,1,"first");
if M ~= -1
Mout = M(:,:);
else
[i,j] = find(FirstID == 1);
for k = 1:16
ii = (ceil(i/4)-1)*4+5;
jj = (ceil(j/4)-1)*4+1;
mm = M(ii:ii+3,jj:jj+3);
mm(isnan(mm)) = -1;
if all(M(i,:)==k)
if all(mm(:)==k)
M(i,j) = k;
end
end
end
end
end
This is the error:
Out of memory. The likely cause is an infinite recursion within the program.
Stephen23 2024 年 4 月 29 日

So check your stopping conditions: are they ever fulfilled?
(When I write "check" I do not mean "rely on what you believe your code is doing", I actually mean check the recursive function calls for its input valus and the stopping conditions. For example, a good start is to print them to the command window. A much better approach is to use the debugger.)

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeVariables についてさらに検索

R2024a

### Community Treasure Hunt

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

Start Hunting!

Translated by