Strings and access to matrix elements

2 visualizaciones (últimos 30 días)
Francesco Sarnari
Francesco Sarnari el 9 de Sept. de 2017
Editada: Stephen23 el 19 de Jun. de 2019
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 comentarios
Stephen23
Stephen23 el 9 de Sept. de 2017
Editada: Stephen23 el 9 de Sept. de 2017
"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
Francesco Sarnari el 9 de Sept. de 2017
Hi Guys, and thanks so much for your replies. This was just an easy example. My objective is to integrate a stochastic differential equation many times in order to obtain N matrices (one for each neuron considered), where each row contains the integration from t=0 to t=tmax and the number rows corresponds to the number of trials I make for the gaussian white noise, and therefore the number of trajectories obtained. As a last step, the solution of my SDE would be an array given by the mean of all rows (in each matrix separately). I would be very grateful to you if you had any additional hint to point me in the right direction. :-)

Iniciar sesión para comentar.

Respuesta aceptada

OCDER
OCDER el 9 de Sept. de 2017
Editada: OCDER el 9 de Sept. de 2017
Ah, we were all inefficient coders at one point. Here's how to implement what the rest are suggesting:
x = -1:0.01:1;
D = repmat({zeros(1, numel(x))}, 1, 5); %Create 1x5 cell that stores zero vectors
for j = 1:length(D)
D{1, j}(1, 2) = 1; %See how this is much better than eval(['D1_' num2str(i) '(1, 2) = 1']);
end
To access your "D1_1" at position (1, 2):
D{1, 1}(1, 2) %Returns 1
  6 comentarios
Stephen23
Stephen23 el 10 de Sept. de 2017
Editada: Stephen23 el 19 de Jun. de 2019
"I now am going to ERASE MY STUPID EVAL and use the logical structure that you all suggested"
That is a good idea.
"Anyways, this is what I was trying to refer to: converting a string representation of a matrix created by mat2str back to a matrix using eval ."
Within code any numeric data should always be stored as numeric data, and when saving to file then with some appropriate file format, so this is going to be a rare occurance anyway. But if you really need to, here is an efficient function without eval:
"so let's not pummel just eval too much."
I do not believe in "pummeling" eval, but I do believe in letting beginners know about its inherent properties, and let them decide if they want to write better code. Even your example is one where eval serves no obvious purpose, and could be easily avoided. Like almost every example that beginners come up with, it turns out that they use eval due to bad code design, rather than bothering how to write simpler, neater, and much more efficient code.
Your example is slow, makes debugging harder, obscures the code intent, removes all code checking tools, and disables JIT optimization (not "pummeling", just statements of fact). The example could be replaced with a simple sscanf (with some indexing and maybe reshape), or by simply avoiding the whole pointless "matrix as a string" representation altogether.
Your example is essentially trying to turn MATLAB into a parser of arbitrary code, which is something we occasionally get questions about. While it is certainly possible to write a parser of arbitrary commands or inputs stored as strings, it will be slow, removes the code checking tools, destroys any JIT optimization, and a often security risk. It is certainly not "pummeling" eval to state such facts.
OCDER
OCDER el 10 de Sept. de 2017
Editada: OCDER el 10 de Sept. de 2017
Ah, I see how controversial eval topic is. I just read more Q&A and a article here. Sorry to open the can of worm!
Thanks Stephen! I'll advise solutions without eval from here on to prevent bad habits from growing.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by