Sum of N matrices
Show older comments
The reason for this new message was to request a new favor.
Is there a code or function in matlab that allows me to add an undefined number (N) of matrices, which I already have a program? As an example I put the following situation to be understood better:
Aux = Mat (1) + Mat (2) + Mat (3) + .... + Mat (n)
I thank you for your attention and I hope you can help me with my predicament.
8 Comments
per isakson
on 28 Jul 2018
Edited: per isakson
on 28 Jul 2018
"undefined number (N) of matrices" How are the matrices stored?
Try this
>> N = 12;
>> M = ones(3,4,N); % N 3x4 matrices
>> aux = sum( M, 3 )
aux =
12 12 12 12
12 12 12 12
12 12 12 12
>>
Pedro Guevara
on 28 Jul 2018
Rik
on 28 Jul 2018
You should change the way you assign your data. Have you read the link Stephen gave you?
Pedro Guevara
on 28 Jul 2018
The program that I already started has been pretty much taken advantage of using the eval function and I do not want to lose all that work.
Why not? That work hasn't helped you. It has hurt you, and will continue to hurt you. I'm willing to bet money that whatever you did with eval can be remade in 1/10th the time using the better practices described at Stephen's link.
Pedro Guevara
on 28 Jul 2018
@Pedro Guevara: the approach using eval is specifically advised against by all experienced MATLAB users and by the MATLAB documentation, which has a whole page explaining why to avoid doing this. It states "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
You have already already wasted more than one day trying to work with this inefficiently designed code, in contrast per isakson gave a much better solution in just a few seconds, which is simpler, neater, more efficient, less buggy, and easier to work with. This is one reason why you should rewrite your code: it will save you time! Do you see the pattern here? If you continue to design your code like this, then you will continue to fight your code for no real benefit. Or you could use arrays and indexing, which is what the MATLAB documentation recommends, and make developing, debugging, and running your code much faster.
Accepted Answer
More Answers (0)
Categories
Find more on Scripts 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!