Is it possible to have an inline function inside a cell array to conditionally return an element to be stored?

3 views (last 30 days)
Diaa on 16 Sep 2020
Commented: Diaa on 2 Oct 2020
Consider I have
mycondition = true;
truestatement = 'yes'; % returned by the inline function when mycondition is true
falsestatement = 'no'; % returned by the inline function when mycondition is false
mycell = {'a' , 'b' , <an inline function to create>};
is it possible to have an inline functrion inside the cell array so that it returns either truestatement or falsestatement without having to do this check outside the cell array and use extra variables?
I know there are different clear ways to do so, but I would like to understand if there is such a way.

Accepted Answer

Rishabh Mishra
Rishabh Mishra on 1 Oct 2020
The cell arrays in MATLAB are fundamental MATLAB classes/data types which have pre-defined definitions. The cell arrays do not support any such feature wherein you can add elements to it after defining an inline function within cell array initialization. To achieve the require purpose, you must add elements to cell array based on conditions that are defined outside the cell array.
Hope this helps.

More Answers (1)

Walter Roberson
Walter Roberson on 1 Oct 2020
Edited: Walter Roberson on 1 Oct 2020
No, but for different reasons.
You are wanting an inline function, when executed, that looks in the current workspace for the value of mycondition, and returns a value selected by it.
That would require that the inline function had no parameters.
However, the internal implementation of inline functions always requires that they accept at least one parameter. The function is not required to do anything with the parameter, but it needs to be passed.
There is no inline function equivalent to
f = @() [falsestatement(repmat(~mycondition,size(falsestatement))), truestatement(repmat(mycondition,size(truestatement)))];
because you cannot implement that () empty parameter list for inline()
If you were willing to have the condition be passed in to the inline function instead of expecting it to be read out from the workspace, then that would be do-able -- provided that the values of falsestatement and truestatement and mycondition could be copied into the inline function instead of being referenced dynamically. But pulling out workspace values dynamically is hard for inline functions.
Why do you want to use inline() ? inline() has been recommended against for a long time.

Sign in to comment.




Community Treasure Hunt

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

Start Hunting!