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

17 ビュー (過去 30 日間)
Erithax
Erithax 2021 年 1 月 28 日
回答済み: Erithax 2021 年 1 月 28 日
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.
  2 件のコメント
Stephen23
Stephen23 2021 年 1 月 28 日
編集済み: Stephen23 2021 年 1 月 28 日
Is there a particular reason why you cannot simply pass the variables as input/outout arguments?
What is the actual goal here? Please explain the context a little more.
Erithax
Erithax 2021 年 1 月 28 日
I'm writing a function that automatically displays the equations of a section in the pretty (~live editor) format. So I don't have to do it via the live editor or via calling pretty(eqn1) for every equation I write. So I'd like it to show in a table with the equation names in the first column, and the equations themselves in the 2nd collumn.

サインインしてコメントする。

採用された回答

Erithax
Erithax 2021 年 1 月 28 日
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.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by