未定义函数或变量 "new_m"

Undefined function or variable "new_m"

我是 Matlab 新手。我有三个功能。当我调用 co.m 和 pol_det.m 时,它们都工作正常。但是,当我调用 minor.m 时,它本身调用 pol_det,而 pol_det 又调用 co.m,我收到一个错误,指的是 co.m: Undefined function or variable "new_m". 我正在使用 R2007b 版本。三个函数如下。最初,它们分别写在一个单独的 .m 文件中。

   function [ k ] = pol_det(a)
%calculates the determinant of a general matrix     (not just consisting of
%numbers) 
dim=size(a); %dimensions of a matrix
if dim(1)~= dim(2)
disp('Only Square Matrices, please')
end

m=length(a);
k=0;
if(m==2)
    k=sum_p(conv(a(1,1),a(2,2)),-  conv(a(2,1),a(1,2))); %calc. the determinant of a 2x2   m. 
else
    for i=1:m
        k=k+((-1)^(1+i))*conv(a(1,i),co(a,1,i));   %calc. the determinant using cofactor expansion
    end
end
if (k==0)
    disp('Matrix non-invertible')
end
end 



    function [ out ] = co( a,i,j )
%cofactor expansion,
%http://people.math.carleton.ca/~kcheung     /math/notes/MATH1107/wk07/07_cofactor_expansion.html
       [m,n]=size(a);
%create a new matrix by eliminating the row and column in which the %element is present
%new_m=zeros(m,n)    
row=1;
    col=1;
    for i1=1:m
        for j1=1:n
            if(i1~=i && j1~=j)
                new_m(row,col)=a(i1,j1);
                col=col+1;
            end
        end
        if(col~=1)
        row=row+1;
        end
        col=1;
    end
    %new_m
    out=pol_det(new_m);
    end



function [ m ] = minor(a)
dim=size(a); %dimensions of a matrix
if dim(1)~= dim(2)
disp('Only Square Matrices, please')
end
a=a.';
for i=1:dim(1)
    for j=1:dim(1)
        a(i,:)=[];
        a(:,j)=[];
        m(i,j)= pol_det(a);
    end
end
end

你的问题是,给定 aij 的某些值,你可能永远不会在初始化 new_m 的循环中输入条件语句.在这种情况下,当您到达以下行 out=pol_det(new_m);.

时,该变量将不存在

您应该在您的循环和条件语句之前为newm设置一个默认值,例如[],这样变量将始终具有价值。您还应该确保 pol_det 可以适当地处理这个默认值。最佳做法是使用 preallocation,既可以提高性能,又可以避免必要变量的条件存在。