Switching functions smartly, like hash map

3 ビュー (過去 30 日間)
Zoe Zhang
Zoe Zhang 2011 年 8 月 24 日
In stead of using multiple if-else or switch-case, is there a way of switching functions smartly?
Take if as an example:
for i = 1 : n
if a
out(i) = function1(p1,p2,p3);
else
if b
out(i) = function2(p1,p2,p3);
else
if c
out(i) = function3(p1,p2,p3);
else
out(i) = function4(p1,p2,p3);
end
end
end
end
Maybe something like funMap = containers.map(key,{function1,...function4}??? So the code will look like:
for i = 1:n
key = ...;
out(i) = funMap(key);
end
Any thoughts? Thanks in advance!

採用された回答

Mike
Mike 2011 年 8 月 24 日
yes, you can use function handles, and str2fun. Here is a simple example:
function out = foo(funOb,p1,p2,p3)
out = funOb(p1,p2,p3);
where funOb would be a function handle. You could also input a string:
function out = foo(funStr,p1,p2,p3)
funObj = str2func(funStr);
out = funOb(p1,p2,p3);
  1 件のコメント
Zoe Zhang
Zoe Zhang 2011 年 8 月 24 日
Thanks a lot!

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2011 年 8 月 24 日
switch p
case a, fu = @function1;
case b, fu = @function2;
case c, fu = @function3;
otherwise fu = @function4;
end
out = fu(p1,p2,p3);
More
k = [a b c];
fu = {@function1 @function2 @function3 @function4};
t = k == p;
out = feval( fu{[t ~any(t)]},p1,p2,p3);
  1 件のコメント
Zoe Zhang
Zoe Zhang 2011 年 8 月 24 日
Thanks a lot, though switch may not work for me this time since my conditions are a little complicated. But great suggestions!

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by