0

我收到一个错误:

b = cellfun(@(x) nansum(mag.*subsref(cross(u{1},x), struct('type', '()', 'subs', {':',':',3})) ),r,'UniformOutput',false);

??? Error using ==> subsref
The "subs" field for the subscript argument to SUBSREF and SUBSASGN must be a cell or character array.

Error in ==> cellcross>@(x)nansum(mag.*subsref(cross(u{1},x),struct('type','()','subs',{':',':',3}))) at 2
    b = cellfun(@(x) nansum(mag.*subsref(cross(u{1},x), struct('type', '()', 'subs', {':',':',3})) ),r,'UniformOutput',false);

Error in ==> cellcross at 2
    b = cellfun(@(x) nansum(mag.*subsref(cross(u{1},x), struct('type', '()', 'subs', {':',':',3})) ),r,'UniformOutput',false); 

谁能告诉我为什么?

我正在使用 Matlab 2011。

4

1 回答 1

3

如果您使用单元格数组作为字段之一调用 struct,您将获得一个结构数组,其中该单元格数组的内容分布在元素上。这发生在struct('type', '()', 'subs', {':',':',3}).

我曾经写过一些代码来绕过这个“特性”:

function newStruct = structWithCell(varargin)
  % Constructs a structure with cell variables as MATLAB would make a struct
  % array by using the equivalent struct() call
  % Setting values to cell() straight away doesn't work unfortunately
  % as MATLAB(R) interprets structs with cell values as a cell array of structs.
  assert(mod(nargin,2)==0,'An even number of arguments is expected');
  newStruct = struct();
  keys      = varargin(1:2:end-1);
  values    = varargin(2:2:end);
  for iKV = 1:numel(keys)
      newStruct.(keys{iKV}) = values{iKV};
  end
end

如果您将调用替换struct为对上述函数的调用,它应该可以正常工作。

或者,您也可以将该部分更改为struct('type', '()', 'subs', {{':',':',3}}). 这样,您将传递一个包含单个元胞数组的元胞数组。这也会得到你想要的。

于 2012-09-08T22:14:13.537 回答