Strings and access to matrix elements
Ältere Kommentare anzeigen
I used the following piece of Matlab code to generate a set of matrices D1_1,...,D1_5:
x=-1:0.01:1;
for i=1:5
eval(['D1_' num2str(i) '=zeros(1,numel(x));'])
end
what shall I do if I now want to assign the value 1 to the i-th value of each matrix? In other words, I'd like to write something like
for i=1:5
D1_i(1,i)=1;
end
but I don't understand which is the right way to do it. I would like to end up with
D1_1(1,1)=1 , D1_2(1,2)=1 , D1_3(1,3)=1 , D1_4(1,4)=1 , D1_5(1,5)=1
Thanks in advance :)
4 Kommentare
Geoff Hayes
am 9 Sep. 2017
Francesco - why do you want to do this? Just use a matrix (or cell array) to store the data for each of these variables. See Stephen Cobeldick's post at Why variables should not be named dynamically with eval for an understanding of why what you are attempting is not a good idea.
"I used the following piece of Matlab code to generate a set of matrices D1_1,...,D1_5:"
Ugh, what a bad way to write code.
"but I don't understand which is the right way to do it."
And that is one reason why it is such a bad idea: it makes code pointlessly complex and hard to understand. Simple tasks, like that one that you are trying to do, become a nightmare.
Why some beginners want to make code as slow, complex, and buggy as possible is a mystery to me.
In any case, do not put meta-data into variable names.
All you need to use is indexing. Indexing is simple, neat, easy to debug, and very efficient. Keep the data in one array and then you will not face any of these pointless problems again. After all the name "MATLAB" comes from "MATrix LABoratory", and not from "lets split the data into thousands of separate variables and make our code totally awful to work with". Learn to use arrays and you will learn how to write neat and simple code. Your choice.
PS: perhaps you might be interested to know what the MATLAB documentation says about your code idea: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended."
You should definitely read this as well:
Francesco Sarnari
am 9 Sep. 2017
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!