matlab:subsref错误

时间:2012-09-08 21:14:39

标签: matlab

我收到错误:

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。

1 个答案:

答案 0 :(得分: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}})。这样,您传递包含单个单元格数组的单元格数组。这也可以满足您的需求。