Alternative for eval, for my case?

조회 수: 8 (최근 30일)
Klaas
Klaas 2015년 9월 14일
편집: Stephen23 2019년 6월 19일
Hellow, I have a lot off variables witch I want to rename from the name they have to the name they have + a new piece witch I define by input of X(to be abel to easy change it). For example now I have typed:
A4optie6a33=A4;
A5optie6a33=A5;
A6optie6a33=A6;
Kostoptie6a33=Kost;
Onderhoudskosten1optie6a33=Onderhoudskosten1;
Onderhoudskosten2optie6a33=Onderhoudskosten2;
Onderhoudskosten3optie6a33=Onderhoudskosten3;
RAAMoptie6a33=RAAM;
Restwaarde1optie6a33=Restwaarde1;
I taught of doing it like this:
X='optie6a33';
eval(['A4' num2str(X) '=A4']);
eval(['A5' num2str(X) '=A5']);
eval(['A6' num2str(X) '=A6']);
...
But this calculation take's al lot of time for watch it has to do I think.
Thanks in advance!
  댓글 수: 3
Stephen23
Stephen23 2015년 9월 14일
@Klaas: today I fixed your formatting, but in future you can do it yourself by selecting the code text and then clicking the {} Code button that you will find above the text box.
Stephen23
Stephen23 2015년 9월 14일
편집: Stephen23 2015년 9월 14일
The best solution is to avoid creating variables with metadata in their names. This awful programming habit makes code slow and unreliable because you have to parse the variable names. Learn how to write code without putting metadata into the variable names and then you don't have to use slow hack solutions like eval to fix it.
Here is a discussion of why you should not include metadata in your variable names:

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

채택된 답변

Arthur Goldsipe
Arthur Goldsipe 2015년 9월 14일
Both eval and num2str are slower than many of their alternatives. Also, I don't see why you're using num2str anyway, since your variable X is already a string.
In any case, you could try using inputname and assignin to rename variables more efficiently. For example, here's a function that will rename a variable by appending a suffix:
function renameWithSuffix(value, suffix)
newName = [inputname(1) suffix];
assignin('caller', newName, value);
end
You could then rename A4 to A4optie6a33 as follows:
renameWithSuffix(A4, 'optie6a33');

추가 답변 (2개)

Stephen23
Stephen23 2015년 9월 14일
편집: Stephen23 2019년 6월 19일

Image Analyst
Image Analyst 2015년 9월 14일
Simply do this:
A4optie6a33 = A4
A5optie6a33 = A5
A6optie6a33 = A6
Then read the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F to learn why it's not a good idea if you have a variable number of variables to assign.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by