How to clear variables created using eval?

I need to use EVAL to calculate a formula in a loop, the formula and the variables involved are just unknown in advance. Then I clear the loaded variables. The problem is that matlab gives 'The current workspace already has too many variables' error after several iterations. But, on checking the workspace, it appears that less than 50 variables are present. I think this has got to do with the eval command. I am guessing that eval is creating multiple copies of 'Vlu' and 'Idx'. I need an idea on how to clear variables created by eval. Before running the program, you need to create a file named as Formula.txt to save formula-strings, one formula lays on one line, such as:
[Vlu, Idx] = max([C345, C123 + C765, C999 * 2]);
[Vlu, Idx] = min([C235, C137 - C222, C259 / 2]);
...
and all vars such as 'C345' have saved in Vars.mat in advance. It should be understood that the following code is just a model while the actual code is much more complex, which has more iterations.
% Read formulas from TXT file, one formula lays on one line
fid = fopen('D:\Formula.txt');
k = 0;
f = fgetl(fid);
while ischar(f)
k = k + 1;
Formula{k} = f;
f = fgetl(fid);
end
fclose(fid);
Rst = zeros(length(Formula), 2); % Result-buffer
for m = 1:length(Formula)
Vars = regexp(Formula{m}, '[C][0-9]\d*', 'match');
% Getting Var-names in a formula
load('D:\Vars.mat', Vars{:}); % Load vars from .mat
eval(Formula{m}); % Error would occur here!
Rst(m, :) = [Vlu, Idx];
for k = 1:length(Vars) % Clear Vars after calculating
eval(['clear(''', Vars{k}, ''')']);
end
end

댓글 수: 6

Image Analyst
Image Analyst 2015년 8월 6일
So just don't use eval(). No other experienced MATLAB programmers ever feel the need to use it. Attach Formula.txt if you want someone to show you how it should be done.
Wang Jian
Wang Jian 2015년 8월 6일
Formular.txt has attached. Still, it's just a simplified model. The reason why I use eval() is that there are nearly a thousand variables in the MAT file, lots of items are calculated with different formulas, and the formulas will be continuously expanded in the future. So I think eval() is a unified way to achieve, avoiding continuously modifying the code structure using 'if... else...'
Stephen23
Stephen23 2015년 8월 6일
편집: Stephen23 2015년 8월 6일
"I need to use EVAL" is the kind of statement that beginners love to use, but usually without understanding that there are much better way to achieve their goals. There is no need to use eval here, simply loading the data into a structure, creating the appropriate arrays and using indexing would achieve the same thing without requiring ugly and buggy eval.
Numbered variables are a good sign that the variables could be easily replaced by standard arrays and indexing. Using eval removes many useful code checking features and makes your code slow and buggy: why would you want to use it when there are much more reliable tools to use?
Typically beginners seem to think that eval solves all of their problems, but as you are discovering it actually just creates more problems...
Wang Jian
Wang Jian 2015년 8월 6일
I really appreciate you for your suggestions, these suggestions will help me to write efficient and reliable code in the future.
However, please forgive me, I still do not know the details on how to achieve. Could you give me a practical example, show me how to load the variables, and execute the formula in stead of buggy eval? Please note that these formulas are inputted externally, which will continue to be added in the future. Thank you very much.
Stephen23
Stephen23 2015년 8월 6일
편집: Stephen23 2015년 8월 6일
It seems that the whole concept should be revised, given that the .mat file contains hundreds of numbered variables and there a an unknown number of formula. How were these variables created? How large are they? How are the formula defined?
The most efficient solution depends on what kind of variables they are, and how they are generated, but I would suggest that instead of creating hundreds of numbered variables simply create some arrays and use indexing. Accessing arrays is fast and easy, and does not cause this kind of problem.
Actually what you are trying to do is to run arbitrary functions on arbitrary data. This is not going to be very efficient use of MATLAB, nor is it going to be robust, nor easy to debug, as you discovered. Every time you use eval you miss out on lots of useful inbuilt tolls that help the code work properly, and give advice on how to make your code faster and more efficient.
Why not just write the formula as an actual MATLAB script and keep the data in arrays. You can easily alter the formula using function handles, and access the data quickly using indexing.
Read this to know more about why you should avoid eval:
Have the file extension be .m . run() the file, or just name it to call it as a script.
Note: if you are using "function" with matching "end", then the script you execute will not be permitted to create new variables -- but it would be permitted to create fields on existing variables. It would also be fine to initialize each of the permitted variables to something (anything, including []) before executing the script.

댓글을 달려면 로그인하십시오.

답변 (2개)

Walter Roberson
Walter Roberson 2015년 8월 6일

0 개 추천

Use fields of a structure. Structures can add fields at need. An appropriate structure is the return value from load()
VS = load('D:\Vars.mat', Vars{:});
Now you can refer to VS.(Vars{K}) if you need to work with the K'th variable, or you can refer by absolute name like VS.apogee3H

댓글 수: 2

Wang Jian
Wang Jian 2015년 8월 6일
Thank you for your answer, but I think it is only a solution on how to load and refer to the unknown variables, I still do not have an idea on how to execute the unknown formula, which contains the unknown variables, and the number of formulas may be increasing. I need a complete solution to replace eval command under these conditions, or a way to get the eval command to work properly. Thank you very much.
Stephen23
Stephen23 2015년 8월 6일
편집: Stephen23 2015년 8월 6일
How are the formula created?
How are the hundreds of numbered variables in the .mat file created?
Look at what you are trying to do: execute each row of Formula.txt with some data. So if Formula.txt contains executable code, why not simply turn it into a script and run that? What is the point in this incredibly inefficient indirect execution of perfectly good executable code?

댓글을 달려면 로그인하십시오.

Image Analyst
Image Analyst 2015년 8월 6일

0 개 추천

Why don't you just do this:
clear all;
? If there are a bazillion named variables, are there any that you want to keep? If so, you can't use clear all. But if you want to just blow all of them away, use clear all.

댓글 수: 1

Wang Jian
Wang Jian 2015년 8월 6일
I'm very careful in using variables, store all of them in .mat, load only necessary variables before execution, and clear them immediately when they turn to unnecessary. But it seems that eval() would leave something in memory within each loop. So after a mount of iterations, memory is exhausted.
'clear all' can not be used in my program, because eval() is used in a loop, at least the Loop variable is still in use.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2015년 8월 6일

댓글:

2015년 8월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by