Alternative for eval, for my case?

12 Ansichten (letzte 30 Tage)
Klaas
Klaas am 14 Sep. 2015
Bearbeitet: Stephen23 am 19 Jun. 2019
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 Kommentare
Stephen23
Stephen23 am 14 Sep. 2015
@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 am 14 Sep. 2015
Bearbeitet: Stephen23 am 14 Sep. 2015
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:

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Arthur Goldsipe
Arthur Goldsipe am 14 Sep. 2015
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');

Weitere Antworten (2)

Stephen23
Stephen23 am 14 Sep. 2015
Bearbeitet: Stephen23 am 19 Jun. 2019

Image Analyst
Image Analyst am 14 Sep. 2015
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.

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by