简体   繁体   中英

Using function handle in lsqr MATLAB

I would like to minimize FT^-1(Ax-B) using lsqr. A is a huge sparse matrix and I defined it using 3 vectors:

RA(L) is the Lth nonzero of A, counting across row 1, then across row 2, and so on;
JA(L) is the column in which the Lth nonzero of A lies;
NA(I) is the number of nonzero coefficients in the Ith row of A.

I computed Ax using a user-defined nested function APROD that I'm trying to pass as a function handle in lsqr. However, it returns an error message: Too many input arguments.

This is my code:

  function x = PROVA
%RA, NA, JA, m are defined here;
mode=1;
x=lsqr(@APROD,B,atol,itnlim);
end


function  result=APROD(x1)
%if mode=1 computes y=y+Ax
%if mode=2 computes x=x+A_(transpose)y
%A is stored in RA,JA,NA by rows

L2=0;
if mode==1
    result=zeros(m,1);
    for c=1:m
       sum=0;
       L1=L2+1;
       L2=L2+NA(c);
       for L=L1:L2
           J=JA(L);
           sum=sum+RA(L)*x1(J);
        end
    result(c)=result(c)+sum;
    end
end

if mode==2
   result=zeros(n,1);
   for c=1:m
       Yc=y(c);
       L1=L2+1;
       L2=L2+NA(c);
       for L=L1:L2
           J=JA(L);
           result(J)=result(J)+RA(L)*Yc;
       end
  end
end
end

This is the error message:

Error using iterapp (line 59)
user supplied function ==> APROD failed with the following error:

 Too many input arguments.

Error in lsqr (line 190)
v = iterapp('mtimes',afun,atype,afcnstr,u,varargin{:},'transp');

Error in PROVA (line 97)
 x=lsqr(@APROD,B,atol,itnlim);

I don't know what I did wrong, it is my first time with function handle, I read other questions about it but I didn't manage to solve my problem. Thank you for your help!

The function handle should take 2 parameters: first one is the solution approx vector, and the second is a char that can be 'notransp' or 'transp' :

function  result=APROD(x1, mode)

        L2=0;
        switch mode
        case 'notransp'
                result = zeros(m,1);
                for c=1:m
                        sum=0;
                        L1=L2+1;
                        L2=L2+NA(c);
                        for L=L1:L2
                                J=JA(L);
                                sum=sum+RA(L)*x1(J);
                        end;
                        result(c)=result(c)+sum;
                end;

        case 'transp'
                result = zeros(n,1);
                for c=1:m
                        Yc=y(c);
                        L1=L2+1;
                        L2=L2+NA(c);
                        for L=L1:L2
                                J=JA(L);
                                result(J)=result(J)+RA(L)*Yc;
                        end
                end
        end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM