Using cellfun with function that can return nothing

7 Ansichten (letzte 30 Tage)
Jerki Jokne
Jerki Jokne am 4 Sep. 2019
Bearbeitet: Guillaume am 4 Sep. 2019
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?

Akzeptierte Antwort

Guillaume
Guillaume am 4 Sep. 2019
Bearbeitet: Guillaume am 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);

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by