Alternative for eval, for my case?

11 ビュー (過去 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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by