sum of all the variables in workspace how to find?

4 ビュー (過去 30 日間)
Seetha Rama Raju Sanapala
Seetha Rama Raju Sanapala 2018 年 2 月 27 日
編集済み: Stephen23 2018 年 2 月 27 日
I have some 100 numbers in the workspace with big names. I want to find the sum of all these variables in the workspace - without writing the big equation for it. Is there a direct way to find the sum of all the numeric variables in the workspace?
  2 件のコメント
Adam
Adam 2018 年 2 月 27 日
編集済み: Adam 2018 年 2 月 27 日
If you want to sum them why are they in individual variables in the first place instead of being in an array, which is the natural place for a bunch of numbers for which taking the sum is an appropriate action?
There may be some horrendous way using 'whos' and 'eval', but I never use eval so I wouldn't know the syntax even if it does exist.
Stephen23
Stephen23 2018 年 2 月 27 日
" Is there a direct way to find the sum of all the numeric variables in the workspace?"
No, there is no direct way to achieve this. And the indirect ways are very bad ways to write code: pointlessly complex, slow, buggy, hard to debug.
Learn to use arrays because that is what MATLAB is for. If you want to learn how to use MATLAB efficiently then use arrays.

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

採用された回答

Noam
Noam 2018 年 2 月 27 日
clear all;
x=10;
y=2;
z=3;
allvariables = whos;
sumOfVars = 0;
for i = 1:length(allvariables)
sumOfVars = sumOfVars + eval(allvariables(i).name);
end
  6 件のコメント
Seetha Rama Raju Sanapala
Seetha Rama Raju Sanapala 2018 年 2 月 27 日
Thank you all for the comments and answers. I have learnt some new things. Also from comments - what to avoid, the bad practices. Both the solution and the comments are new learning for me.
Stephen23
Stephen23 2018 年 2 月 27 日
編集済み: Stephen23 2018 年 2 月 27 日
"what to avoid, the bad practices"
e.g. putting all of your data into lots of separate variables and then using eval.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 2 月 27 日
No there is no direct way to do that. You should avoid the problem by not using separate variables for them to begin with.
Adding all the variables is possible but the cleanest approach is probably to save the workspace to a file and to load the file into a struct and use one of several ways to add the fields to the struct.

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by