switch statement to select a function

1 次查看(过去 30 天)
I have select one out of four functions, decided by the value of variable named "Indicator", which can be applied to a matrix Y as follows
ReceivedY = isequal(Indicator,1).*Y
ReceivedY = isequal(Indicator,2).*flipud(Y)'
ReceivedY = isequal(Indicator,3).*flipud(fliplr(Y))
ReceivedY = isequal(Indicator,4).*rot90(Y,1)
I want to write a function which takes in Indicator and gives me back newY depending upon the value of Indicator
NewY = somefunction(Y,Indicator)
I option is to use switch statements...but I have to repeat this thing many times so I am reluctant to use this option. What else can I do

采纳的回答

Walter Roberson
Walter Roberson 2013-3-29
funs = {@(Y) Y, @(Y) flipud(Y)', @(Y) flipud(fliplr(Y)), @(Y) rot90(Y,1)}
ReceivedY = funs{indicator}(Y);
  2 个评论
xplore29
xplore29 2013-3-29
thanks a lot.....it works like magic. I had never heard of any such thing before.
Walter Roberson
Walter Roberson 2013-3-29
You can improve performance as follows:
persistent funs
if isempty(funs)
funs = {@(Y) Y, @(Y) flipud(Y)', @(Y) flipud(fliplr(Y)), @(Y) rot90(Y,1)}
end
ReceivedY = funs{indicator}(Y);
This will prevent the code from having to recreate the anonymous functions each time.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Types 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by