# calling the function dynamically - is it possible using eval or evalin

31 ビュー (過去 30 日間)
Gopalakrishnan venkatesan 2016 年 8 月 31 日

function data(k)
k = {sum,multiply,divide};
for l=1:numel(k)
[a,b,c] = data_sum(d,e)
end
end
The function data calls the another function called data_sum. Now i need to change the function name on every loop i.e data_multiply, data_divide. These functions also has the same number of input and output arguments as data_sum.
Is it possible to solve the above problem using eval, evalin or some other way ?
Thanks a lot

サインインしてコメントする。

### 採用された回答

Stephen23 2016 年 8 月 31 日

The best solution would be to learn how to use function handles, and then simply create the cell array to have function handles instead of strings:
>> C = {@mtimes,@rdivide,@max};
>> for k = 1:numel(C), C{k}(2,3), end
ans =
6
ans =
0.6667
ans =
3
Generate function handles from strings If the function names really must be generated from strings, then use str2func to generate the function handles first, then call it as above:
>> S = {'mtimes','rdivide','max'};
>> C = cellfun(@str2func,S,'UniformOutput',false);
Avoid eval and evalin and assignin
Learn to avoid using eval and other functions that let beginners write slow buggy code:

サインインしてコメントする。

### その他の回答 (1 件)

Thorsten 2016 年 8 月 31 日
If you just have three functions, it's best to use
[a,b,c] = data_sum(d,e)
[a,b,c] = data_multiply(d,e)
[a,b,c] = data_divide(d,e)
##### 1 件のコメント表示非表示 なし
Gopalakrishnan venkatesan 2016 年 8 月 31 日
No i have lot of function. May be around 20

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!