# Is there the more elegant way to do this?

9 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
E1=sum(A1);
E2=sum(A2);
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 CommentShow -1 older commentsHide -1 older comments
Stephen23 on 10 Aug 2017
Edited: Stephen23 on 15 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: https://www.mathworks.com/help/matlab/matlab_prog/string-evaluation.html
Read this to know more:
See KSSV's much simpler, more efficient answer.

Sign in to comment.

### Accepted Answer

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 sum..you can specify dimension there and you can apply this function on 3D matrix also.
A = rand(10,24,10) ;
B = sum(A) ;
##### 3 CommentsShow 1 older commentHide 1 older comment
KL on 11 Aug 2017
+1
Jan on 11 Aug 2017
Edited: 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.

### More Answers (3)

Walter Roberson on 10 Aug 2017
##### 5 CommentsShow 3 older commentsHide 3 older comments
Jan on 12 Aug 2017
@Stephen: Please copy this nice analysis to the thread why-variables-should-not-be-named-dynamically-eval
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?
##### 3 CommentsShow 1 older commentHide 1 older comment
Jan on 11 Aug 2017
Edited: Jan on 15 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 Doke on 15 Aug 2017
Edited: Jiro Doke 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.

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.
1.
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) ')'];
evalin('base',str1)
end
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
##### 13 CommentsShow 11 older commentsHide 11 older comments
Jan on 12 Aug 2017
Edited: 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.
Stephen23 on 12 Aug 2017
Edited: Stephen23 on 13 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: https://www.mathworks.com/help/matlab/matlab_prog/techniques-for-improving-performance.html
"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.

### Categories

Find more on Historical Contests in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!