将类转换为双

时间:2016-12-31 10:51:52

标签: matlab class indexing double

我有一个自定义类,它通过以下方式将值与衍生物组合在一起:

>> Params.betah
value =
   0.978961862737933
Size: (1,2)
   1.000000000000000   1.000000000000000  -0.001934834924361

当我在我的代码的特定部分使用此变量时,我得到一个'从转换为double的转换是不可能的。' (deriv1是类的名称)。

因此,在代码的这一部分中,我将感兴趣的是只有值的变量。出于某种原因,我无法弄清楚如何做到这一点。

该类的定义如下:

% Matlab file to implement class "deriv1",
% forward mode of automatic differentation, first derivatives, possibly ssparse
% Usage:
% 1) x = deriv1(val): val is column vector
%    x is vector of independent variables, Jacobian is the identity
% 2) x = deriv1(val,iIndep): val is column vector, iIndep index of variables
%    x is vector where iIndep are independent variables, rest are constants
% 3) x = deriv1(val,0,np): val any matrix, np positive integer
%    x has zero Jacobian, assuming np independent variables
% 4) x = deriv1(val,[],J): val any matrix, J the Jacobian
%    x is matrix of values with Jacobian J
function s= deriv1(val,iIndep,deriv)
  nSparse = 1;
  if(nargin==0 | nargin>3)
    error('usage: deriv1(Value,Derivative)');
  end
  s.v=val; 
  if nargin==3
    if(isscalar(iIndep) && iIndep==0)
      np = deriv;
      if(np>=nSparse)
    s.d = ssparse(prod(size(val)),np);
      else
    s.d = zeros(prod(size(val)),np);
      end
    else
      s.d=ssparse(deriv);
    end
  else % only one argument
    m=size(val);
    if(length(m)~=2 | m(2)~=1)
      error('single argument to deriv1 must be column vector (independent variables)');
    end
    if(nargin==1)
      iIndep = 1:m(1);
    end
    nIndep = length(iIndep);
    if(nIndep>=nSparse | issparse(val))
      s.d=ssparse(iIndep,1:nIndep,ones(nIndep,1),m(1),nIndep);
    else
      s.d=zeros(m(1),nIndep);
      s.d(iIndep,:)=eye(nIndep);
    end
  end

  s=class(s,'deriv1');

但如果我尝试访问Params.betah.v,我会收到此错误:

Error using deriv1/subsref (line 11)
wrong index type for_ deriv1

代码如下所示:

function xout=subsref(x,s)
  nx = size(x);
  switch s.type
    case '()'
      % xout.v = x.v(s.subs{:});
      xout.v = subsref(x.v,s);
      Is = reshape(1:prod(size(x.v)),size(x.v));
      ii = subsref(Is,s);
      xout.d = x.d(ii(:),:);
    otherwise
      error('wrong index type for_ deriv1');
  end

  if(nnz(xout.d)==0)
    xout = xout.v;
  else
      xout = class(xout,'deriv1');

  end

我对Matlab很新,并没有自己编写这部分代码。谁能告诉我如何创建一个只包含原始变量中包含值和派生值的变量?

0 个答案:

没有答案