Matlab 中 strcat 后的未定义函数或变量
Undefined function or variable after strcat in Matlab
我有一个函数向量,我正在尝试从中获取子集。我将向量中的函数转换为元胞数组,以便我可以对其进行索引。这是脚本
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));
但是我在测试功能时出错。它说 coeff1
未定义。不知何故,解析函数无法识别它。有什么问题吗?
提前致谢。
正如@excaza 指出的那样,使用 str2func
生成的函数无法访问不在其工作区中的变量。这给您留下了两个解决方法:您可以将出现的变量名称替换为 strrep
或 regexprep
的值:coeff1
变为 (1)
,等等。或者您可以存储所有系数在一个向量中并将它们作为第二个参数传递:
F = @(x, coeff) [...
coeff(1)*x(1)*x(4); ...
这仍然让您处理字符串操作和函数句柄操作。两者都很昂贵且容易损坏。由于您最初的问题略有不同,并且特别提到您想要速度,所以让我建议一种不同的方法:
您的示例表明 F
具有特定结构,即每一行都是 x
的特定元素乘以常数的乘积。
在这种情况下,您可以根据需要利用此结构生成函数句柄:
% 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)
所以 F
是给定行索引的函数,returns 可以应用于 x
.
的函数
我有一个函数向量,我正在尝试从中获取子集。我将向量中的函数转换为元胞数组,以便我可以对其进行索引。这是脚本
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));
但是我在测试功能时出错。它说 coeff1
未定义。不知何故,解析函数无法识别它。有什么问题吗?
提前致谢。
正如@excaza 指出的那样,使用 str2func
生成的函数无法访问不在其工作区中的变量。这给您留下了两个解决方法:您可以将出现的变量名称替换为 strrep
或 regexprep
的值:coeff1
变为 (1)
,等等。或者您可以存储所有系数在一个向量中并将它们作为第二个参数传递:
F = @(x, coeff) [...
coeff(1)*x(1)*x(4); ...
这仍然让您处理字符串操作和函数句柄操作。两者都很昂贵且容易损坏。由于您最初的问题略有不同,并且特别提到您想要速度,所以让我建议一种不同的方法:
您的示例表明 F
具有特定结构,即每一行都是 x
的特定元素乘以常数的乘积。
在这种情况下,您可以根据需要利用此结构生成函数句柄:
% 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)
所以 F
是给定行索引的函数,returns 可以应用于 x
.