How can save the output of the eval function

조회 수: 9 (최근 30일)
Lukas Henzinger
Lukas Henzinger 2018년 1월 3일
편집: Kathryn Bennett 2018년 4월 29일
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?

채택된 답변

Manan Mishra
Manan Mishra 2018년 1월 9일
편집: Manan Mishra 2018년 1월 9일
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.

추가 답변 (1개)

Kathryn Bennett
Kathryn Bennett 2018년 4월 29일
편집: Kathryn Bennett 2018년 4월 29일
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')

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by