sum element of several matrix
Show older comments
I have 100 matrix (mxm). I want to sum each element, in order to obtain a matrix with same dimension (mxm)of the 100 I have already got.
SUM(1,1)=A(1,1)+B(1,1)+.....+N(1,1)
SUM(2,1)=A(1,1)+B(2,1)+.....+N(2,1)
Sum(N,N)= A(N,N)+B(N,N)+.....+N(N,N)
hopefully is clear.
7 Comments
Adam
on 4 Jul 2018
Why do you have 100 matrices? This is your problem. If you had 1 matrix of size m x n x 100 then your problem would be easy.
As it is you can achieve it by hard coding your 100 matrix names into a sum.
Or you can step back and change whatever gave you 100 individual matrices in the first place and make it give you just 1 3d array.
The best solution, as Adam already mentioned, is to store your data in one MxNx100 array. Then all you need to do is this:
sum(arr,3)
and your task would be finished. Simple, efficient code though better data design.
Storing data in lots of separate matrices massively complicates any task, requiring slow, complex code, which is harder to debug. Rather than having lots of variables, use basic MATLAB indexing to allocate your imported/created data into one array. After all, it is much better to fix the problem at the source than write some hack code to fix all the following problems it causes:
Davide Di Pasquale
on 4 Jul 2018
Adam
on 4 Jul 2018
How did you get them in the first place?
Stephen23
on 4 Jul 2018
@Davide Di Pasquale: how did you get them in the first place? I guess you load-ed them, in which case you can start to fix your code by load-ing into an output variable:
S = load(...)
after that depends on the fieldnames.
Guillaume
on 4 Jul 2018
the problem is the these matrices are generated inside a loop. So it is not straightforward do what you suggested. Regards
Guillaume
on 4 Jul 2018
It is trivial to change your loop so that it does not generate all these matrices. In fact, you must have gone through some hoops just to generate these individual matrices.
Show us your loop code and we'll show you how to simplify it.
Answers (0)
Categories
Find more on Logical 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!