Undefined function or variable after strcat in Matlab

爷,独闯天下 提交于 2019-12-12 03:34:36

问题


I have a vector of functions and I am trying to obtain subsets from it. I transform the functions in the vector into a cell array so that I can index into it. Here is the script

coeff1 = 1;
coeff2 = 2;
coeff3 = 3;

F = @(x) [... 
coeff1*x(1)*x(4); ...
0; ...
coeff2*x(3); ... 
coeff3*x(7)*x(3) ...
];

G = regexp(func2str(F), ';|\[|\]', 'split');
H = cellfun(@str2func, strcat(G{1}, G(2:end-1)), 'uni', 0);
F2 = @(y)cellfun(@(x)x(y),H(2:4));
F2(rand(1,4));

But I get an error when testing the function. It says coeff1 is undefined. Somehow the parsed function does not recognize it. What could be wrong?

Thanks in advance.


回答1:


As @excaza has noted, functions generated with str2func do not have access to variables not in their workspace. That leaves you with two workarounds: you could replace occurrences of variable names with the value with strrep or regexprep: coeff1 becomes (1), etc. Or you could store all coefficients in one vector and pass them as a second argument:

F = @(x, coeff) [... 
coeff(1)*x(1)*x(4); ...

That still leaves you to deal with string operations and function handle operations. Both are costly and prone to breaking. Since your original question is slightly different, and specifically mentions that you want speed, let me suggest a different approach:

Your example suggests that F has a particular structure, namely that each line is the product of particular elements of x, multiplied by a constant. In that case, you can utilize the this structure to generate function handles as you need them:

% Coefficient matrix for x. Along second dimension, 
% elements of x will be multiplied with these factors. Along third
% dimension, these products (multiplied with the corresponding item of C)
% will be summed. 

X = logical(cat(3, ...
  [  1     0     0
     0     1     1
     0     0     0
     0     0     0
     1     1     1  ], ...
  [  0     0     0
     1     0     0
     0     0     0
     0     0     1
     0     0     0  ]));

% coefficients for each row
C = [ 1, 2
      2, 3
      0, 0
      0, 3
      1, 0 ];

% anonymous function generating anonymous functions for particular rows
F = @(ind) @(x) sum(C(ind, :) .* squeeze(prod(bsxfun(@times, X(ind, :, :), x) + ~X(ind, :, :), 2)), 2);
% get one of those functions and test
newF = F([2 4]);
x = [1, 2, 3];
newF(x)

allF = F(':');
allF(x)

So F is the function that, given row indices, returns a function that can be applied to x.



来源:https://stackoverflow.com/questions/36289476/undefined-function-or-variable-after-strcat-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!