matlab中stract用法_在Matlab中使用strcat之后未定义的函数或变量

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值