MATLAB Answers

Is there the more elegant way to do this?

32 views (last 30 days)
MUKESH KUMAR on 10 Aug 2017
Edited: Jan on 15 Aug 2017
I have 10 matrices(10*24 size each) named A1,A2,,,,A10.Now i want this
till E10=sum(A10);
thus E1,E2,,,,,E10 each matrices size of 1*24 . so there is another way to write in short code ?

  1 Comment

Stephen Cobeldick
Stephen Cobeldick on 10 Aug 2017
"I have 10 matrices(10*24 size each) named A1,A2,,,,A10"
Well, that is a bad way to write code: trying to access those variables dynamically will be slow, buggy, obfuscated, hard to debug, etc.
"Is there the more elegant way to do this?"
Yes, there is! It would be much simpler to put all of your data into one array, then your code will be simple, efficient, neat, easy to debug, etc, etc. Some other beginners will tell you to magically create variables, but instead you might like to read what the MATLAB documentation has to say about that: "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." (this advice also applies to evalin and assignin. source:
Read this to know more:
See KSSV's much simpler, more efficient answer.

Sign in to comment.

Accepted Answer

John BG
John BG on 10 Aug 2017
Edited: John BG on 11 Aug 2017
Hi Mukesh Kumar
Elegance like beauty lives in the eyes of the observer, so while some people abhor the command evalin, I consider it's a really powerful and elegant option to simplify the generation of variables.
Simulating data
A1=randi([-10 10],3)
A1 =
-2 4 -10
3 -10 -8
-7 -5 7
>> A2=randi([-10 10],3)
A2 =
4 -10 6
-4 -1 6
9 -2 -7
>> A3=randi([-10 10],3)
A3 =
0 4 4
-1 5 3
3 -5 -7
2. Code that writes code
for k=1:1:3
str1=['E' num2str(k) '=sum(A' num2str(k) ')'];
E1 =
-6 -11 -11
E2 =
9 -13 5
E3 =
2 4 0
if you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance
John BG


John BG
John BG on 12 Aug 2017
If you all consider that the command evalin has problems,
have you already reported to Mathworks?
If so, what has been the answer?
So, just for the understanding of the readers, in your opinion:
Stephen Cobeldick, Jan Simon, Adam
all problems related to command evalin, do come from highly likely ill-posed input data, but it is always a problem of the command evalin?
in any case, why do you choose to ignore the human factor for this command, yet we all know that it must always be considered when attempting to solve MATLAB questions?
Jan on 12 Aug 2017
@John BG: Nobody claims, that evalin has a problem or bug, but it is inefficient by design. This cannot and need not be fixed, because it is the nature of this command. You cannot fix the language to avoid a forgotten pre-allocation also, or a hammer, when you hit on your thumb: The user is responsible for a careful work.
If you read the links, which have been posted already, you know MathWorks answers, e.g. Loren: evading eval and Matlab docs: Why Avoid the eval Function?.
Nobody ignores the additional mistakes in the construction of the string to be evaluated. But fixing the string is a too short-dated solution only, because the inherent problems remain - and they have been explained more then enough already.
You decide if you ignore or consider the clear and exhaustive arguments given by experienced programmers and MathWorks. We will proceed to explain the concerning drawbacks to beginners and teach good (better!) programming practices.
If you are interested in reputation points: eval got 4 points, and 20 for eval free suggestions.
Obviously, no new serious arguments occur in this discussion anymore and I leave it.
Stephen Cobeldick
Stephen Cobeldick on 12 Aug 2017
"If you all consider that the command evalin has problems"
No one has said that the command itself is buggy, because the problems are simply inherent in what it does. The problems with evalin and its relatives are much more general and are not even specific to MATLAB: the issues are fundamental to how JIT compilers work, about the inefficiency of string evaluation, about how static code checking works, about how objects are identified in workspaces, about interference between threads or workspaces, about the risks of evaluating arbitrary code, and other aspects of high-level computing. Together these cause code that uses evalin (and eval, etc.), to be buggy, slow, unreliable, a security risk, hard to debug, obfuscated, etc., etc..
"have you already reported to Mathworks? If so, what has been the answer?"
Seriously, anyone can read the documentation: "Avoid functions such as eval, evalc, evalin, and feval(fname)". source:
"in any case, why do you choose to ignore the human factor for this command, yet we all know that it must always be considered when attempting to solve MATLAB questions?"
We do consider the human factor: the factor that your own example clearly shows how using evalin turned a bug in a trivially simple one-line piece of code into something that the user could not solve by themselves. And that is why we recommend people to use methods that are simpler, faster, less buggy, easier to debug, more reliable, more secure, where the MLINT and Editor warnings help them, etc., etc. Which just happen to be the same methods that the MATLAB documentation recommends.
"...while some people abhor the command evalin, I consider it's a really powerful and elegant option to simplify the generation of variables."
You still have not explained why writing slower, buggier, inefficient, hard-to-debug, insecure code is "elegant". You have provided us with one example of where a user got completely flummoxed trying to fix code that used exactly that buggy and hard-to-debug coding method that you call "elegant" (code that should have been trivial to fix). I would be interest what magic secrets you know about evalin that no one else knows (including the authors of MATLAB who wrote the documentation advising to avoid evalin).

Sign in to comment.

More Answers (3)

KSSV on 10 Aug 2017
Edited: KSSV on 10 Aug 2017
You make A1,A2,...A10 matrices a 3D matrix while computing or defining them..and the call sum..
Read about can specify dimension there and you can apply this function on 3D matrix also.
A = rand(10,24,10) ;
B = sum(A) ;


Stephen Cobeldick
Stephen Cobeldick on 11 Aug 2017
+1 simple and perfect. Nice work, KSSV.
Jan on 11 Aug 2017
+1. Exactly: 3D arrays solve the problem very efficiently from the view point of clarity and maintainability of the code, as well as concerning the run time.

Sign in to comment.

Walter Roberson
Walter Roberson on 10 Aug 2017


Show 2 older comments
Stephen Cobeldick
Stephen Cobeldick on 12 Aug 2017
@John BG: thank you for bringing that question to our attention.
That question illustrates very well the problems that evalin causes, and shows that these problems are not caused by the "inadequate structuring of the data" as some beginners believe, but are actually caused by the command itself. Lets have a look:
  • buggy: well, clearly the code has a bug as the code does not do what the author wants.
  • hard to debug: even though what they are trying to do something that should be trivially simple (suppress display in the command window), by using evalin they could not figure out how to achieve even this simple goal.
  • obfuscated: they could not figure out how to fix the bug because the actual purpose of the code is hidden amongst a whole line of apostrophes and strings. The real purpose is hidden and the evalin is just a distraction.
  • removes all code checking tools: if the user had chosen to write code without evalin then the MATLAB editor would provide a warning to put a semi-colon at the end of the line, gives advice on how to fix it, and even has an auto-fix button:
  • slow: this has nothing to do with the "data structure", but is due to JIT not being able to work at all with evaluated strings. By using evalin the author made their code slower than it needs to be.
  • security risk: without knowing it the author increased the risk of arbitrary code being evaluated.
  • etc, etc.
So there you have it: a perfect example of what should have been trivially simple task made pointlessly complicated by using evalin. The author got totally confused trying to do something that should have been easy, could not resolve their own incredibly simple piece of code, got no helpful advice from the Editor (because code hinting and warnings do not work with evaluated strings), and had to resort to asking on an internet forum. What a waste of time!
If they had written better code (such as what Jan Simon answered) then they would have found it much easier to understand their own code, it would be more efficient (without them even having to think about it), and the editor itself would have warned them to add a semi-colon.
What a great example of how using evalin is a total waste of time! Thank you for bringing it to our attention, it illustrates the points we are making quite well.
"For instance, Misha suggests evalin in this question"
Misha does not suggest evalin anywhere in their answer: the OP was already using evalin.
Walter Roberson
Walter Roberson on 13 Aug 2017
"why is Mathworks keeping command evalin, and other similar commands, in the common toolbox"
Because evalin() is required to implement "syms" and cplex, and to make it possible for various graphical tools such as the curvefitting tool or Simulink to retrieve user-defined values without the user having to pass in everything that might be needed.

Sign in to comment.

Jan on 11 Aug 2017
Edited: Jan on 11 Aug 2017
Not an answer, but a comment concerning the discussion:
This is another example for an inefficient debate: The group of experienced Matlab programmers provide profound arguments, and one person insists on claiming the opposite and suggesting it to beginners. Neither code examples, nor timings, nor references in Matlab's documentation can force somebody to change his opinion. But some contributors, as me, still spend time to post the important details to warn other beginners not to get trapped by the pitfall of eval.
There is a common sense about good programming practices. Voting for good solutions helps to share this knowledge. Currently there are 9 votes for the good solution, and 0 vote and 1 acceptance for a bad solution. All readers can draw their own conclusions. The only problem is, that the accepted status has such a prominent position and shiny green check mark.
The editors can un-accept an answer, but they use this power very rarely for good reasons. The drawback for the forum would be reduced, if e.g. 4 votes (of maybe MVP members) move an answer on top of the accepted one.
It will not be possible to convince all forum members to suggest good programming practices. Discussing the same point with the same person again, will not help. What can we do instead to support the quality of the forum's contents?


Adam on 11 Aug 2017
I think constantly linking to relevant threads, including tutorial threads is still the best practice. People who want to learn good programming will see that if they search, but those who don't wish to learn and want a quick fix to their immediate problem won't. That's up to them ultimately. Someone creating dynamically named variables will repeatedly come up against problems they struggle to solve or that they manage to solve until their code becomes so buggy they don't understand how it works. Then they'll give up or come back here and ask further questions. If they still don't learn they are just a lost soul to Matlab. It happens.
Ultimately though the Accepted Answer status has to be as it is because this thread is for the person who asked the question firstly. If they feel that an answer fulfils their needs, however misguided, then that is the answer to accept. There are so many threads like this that a majority of them contain the same links to places to learn.
Of course a thread is also important for future learning, but when it is such a common subject as this one individual thread is just a drop in the ocean. Only the specific tutorial threads, FAQ, etc can be considered as global answers. If people don't search hard enough then they aren't sufficiently interested to learn.
And sometimes people learn best by taking an initially easy seeming route to solve their immediate problem, only to see how much difficulty it lands them in. Learning by failure often sticks in the memory far better than just regular learning of a good solution first time round.
It would be good though if there could be a small handful of sticky threads (or even just one with links to the tutorial threads and others like them) in the forum though. Not a load though as a mass of sticky threads is just annoying. I know there is an FAQ somewhere, but even I never have a clue where to find that after 5+ years in the forum, without resorting to a regular Google search for it.
Jan on 11 Aug 2017
@Adam: I agree. The OP Mukesh did get enough information here and he will learn it sooner or later. But especially because the thread is for the author, it can be useful to emphasize a better solution than the accepted one. Nothing is lost for the author if the order is changed by votes, because he or she knows already, which answer was accepted.
The problem of the multiple meaning of the accepted status has been discussed already: 1. solved my problem. 2. thread can be closed, 3. good solution.
Including the FAQ and/or a list of sticky threads is a really good idea. More than 50% of the forum's interface are empty space, so there is more than enough space for an impressive link. A prominent location in the header [... Ask Answer Browse More ->FAQ<- Help] would be fine.
Then it is useful already to append a comment "Better solution: see [link: FAQ]" under a bad suggestion. This seems much more efficient than these fruitless discussions.
I request, that Stephen's Tutorial is included in this list. :-)
jiro on 15 Aug 2017
I'm commenting as a user, not as a MathWorks staff (despite the little indicator by my name). It would be nice that if a thread has an answer with "significantly more" votes than the accepted answer, there is an indication on that page about it. Perhaps a hyperlinked asterisk by the accepted answer that points to that popular answer.

Sign in to comment.