How can save the output of the eval function

5 views (last 30 days)
I want to assign an unknown amount of points to an unknown amount of variables in the order of characters, the problem is the variables aren't saved to my workspace. My code so far:
function eingabe_mehrerer_punkte( )
s = 'a':'z';
for ns = 1:length(s)
u = s(ns);
point=input( 'specify a point: ');
eval([u '= point'])
question = input( 'next point (j/n) ?', 's' );
if( question == 'n')
break
end
end
How can this be done?

Accepted Answer

Manan Mishra
Manan Mishra on 9 Jan 2018
Edited: Manan Mishra on 9 Jan 2018
You should consider an alternative approach to this problem. Creating variables dynamically is a common and frequent source of errors. Additionally, it is a slow process.
Although the eval function is very powerful and flexible, it is not always the best solution to a programming problem. Code that calls eval is often less efficient and more difficult to read and debug than code that uses other functions or language constructs.
Please refer the following documentation link for more details:
One of several alternative approaches could be to use structures.
function S = eingabe_mehrerer_punkte( )
s = 'a':'z';
S = [];
for ns = 1:length(s)
point=input( 'specify a point: ');
S.(s(ns)) = point;
question = input( 'next point (j/n) ?', 's' );
if( question == 'n')
break
end
end
Then you can call the function as:
>> char_struct = eingabe_mehrerer_punkte( )
This would return the structure "char_struct" with the fields as consecutive alphabets.

More Answers (1)

Kathryn Bennett
Kathryn Bennett on 29 Apr 2018
Edited: Kathryn Bennett on 29 Apr 2018
I've also struggled with this, and wanted to save my outputs to the same matfile as individual matrices, as I didn't want to change the rest of my scripts to load parts of structures. I found this works:
>>matfile = fullfile(folder, filename); >>eval(['EMG_' num2str(muscle) '=EMG;']); % rename the variable >>EMG_epochs = sprintf('EMG_%s', muscle);% create a character string with the same new variable name save(matfile,EMG_epochs,'-append')

Tags

Community Treasure Hunt

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

Start Hunting!