MATLAB: How to get all workspace variables with their respective value from within a function

functionMATLAB

Say I have some variables
var1 = 3;
str2 = "MATLAB";
syms x y
eqn1 = x + y;
Say I want to get all the variables in this workspace with their respective values from within some function:
function listVars()
allVarNames = evalin( 'base', 'who' )
allVarValues = ???
t = table(allVarnames, allVarValues)
end
Is this possible? If not, is it possible if the variables are of the same type?
———————————————-
I already tried ??? =
evalin('base','allVarNames')
%and

evalin('base',allVarNames)
But these result in these errors respectively:
Error using evalin
Unrecognized function or variable 'allVarNames'.
%and
Error using evalin
Must be a text scalar.

Best Answer

I was able to solve it myself by using a for-loop and the string() function:
function listVars()
allVarNames = evalin( 'base', 'who' )
for i = 1:1:numel(allVarNames)
allVarValues(i) = evalin('base',string(allVarNames(i)))
end
allVarNames = string(allVarNames)
allVarValues = string(allVarValues)'
table(allVarNames,allVarValues)
end
NOTE: If the first variable (alphabetically) is not a symbolic variable, but there are other symbolic variables then this code will throw an error because then allVarValues doesn't have the right type to handle symbolic variables.