How can save the output of the eval function

5 Ansichten (letzte 30 Tage)
Lukas Henzinger
Lukas Henzinger am 3 Jan. 2018
Bearbeitet: Kathryn Bennett am 29 Apr. 2018
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?

Akzeptierte Antwort

Manan Mishra
Manan Mishra am 9 Jan. 2018
Bearbeitet: Manan Mishra am 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.

Weitere Antworten (1)

Kathryn Bennett
Kathryn Bennett am 29 Apr. 2018
Bearbeitet: Kathryn Bennett am 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')

Kategorien

Mehr zu Workspace Variables and MAT-Files finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by