Alternative for eval, for my case?

12 次查看(过去 30 天)
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 中查找有关 Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by