Using cellfun with function that can return nothing
11 views (last 30 days)
Show older comments
I am trying to use the cellfun function to execute the evalin function on a cell array of char vectors, which correspond to elements in the base workspace. Sometimes the char vectors are empty, in order to ensure the order of the elements matches with other cell arrays of data.
a = Simulink.Signal;
b = Simulink.Signal;
C = {'a', '', 'b'};
X_values = cellfun(@(x) evalin('base', x), C, 'UniformOutput', false);
Executing the last line gives the error:
Error using @(x) evalin('base', x)
Error: This statement is incomplete.
Is seems that the issue is that evalin returns nothing when it does not find the '' in the base workspace. Is there some way to make the cellfun work in this case, or do I need to use a loop?
0 Comments
Accepted Answer
Guillaume
on 4 Sep 2019
Edited: Guillaume
on 4 Sep 2019
I'm not going to comment on the wisdom of using evalin.
The problem is not with cellfun. You'll get the same error if you do:
val = evalin('base', '');
The error message could be better as it looks like you're seeing an implementation detail of evalin, but clearly, '' is not allowed as an input for evalin.
The workaround would be to create your own wrapper that catches errors with evalin (would also help if the variable name you pass is not actually a variable):
function value = evalin_with_catch(varname) %no point in asking for the workspace. It can only be base here
try
value = evalin('base', varname)
catch
value = 'INVALID VARIABLE'; %whatever value you want returned.
end
end
then:
X_values = cellfun(@evalin_with_catch, C, 'UniformOutput', false);
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!