未定义的函数或变量“ new_m”

时间:2019-03-05 14:57:45

标签: matlab function variables undefined call

我是Matlab的新手。我有三个功能。当我致电co.m和pol_det.m时,它们都可以正常工作。但是,当我调用minor.m本身又调用pol_det时,而pol_det又调用了co.m时,我得到一个错误,该错误引用了co.m:未定义的函数或变量“ 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

1 个答案:

答案 0 :(得分:1)

您的问题是,给定aij的某些值,您可能永远不会在初始化new_m的循环内输入条件语句。在这种情况下,当您到达下一行out=pol_det(new_m);时,该变量将不存在。

您应在循环和条件语句之前,为newm 设置默认值,例如[],以便变量始终具有一个值。您还应确保pol_det可以正确处理此默认值。最佳实践是利用preallocation,既可以提高性能,又可以避免有条件地存在必要的变量。