1

I have a 7x21 matrix called A. Within this matrix there are three equally sized 7x7 submatrices. I call them B,C and D, where B = A(:,1:7), C = A(:,8:14) and D = A(:,15:21).

How can I produce a matrix E which is also 7x7 matrix where simply B, C and D are added up, i.e. E = B+C+D.

Thanks a lot for your help!

2 Answers 2

2

Generic code to get such an output -

N = 3; %// Number of submatrices
[m,n] = size(A) %// Get size [no. of cols must be multiple of N
E = reshape(sum(reshape(A,m*n/N,[]),2),m,n/N)
8
  • 1
    thanks a lot Divakar! That was exactly what I was searching for!
    – rookieMI
    Sep 9, 2014 at 20:19
  • 1
    +1 You can do with just one reshape: E = sum(reshape(A, [m n/N N]), 3);
    – Luis Mendo
    Sep 9, 2014 at 20:32
  • 1
    @LuisMendo Thanks, good suggestion! Well recently I have been trying to keep it 2D wherever possible. Would be interesting to see which one works better.
    – Divakar
    Sep 9, 2014 at 20:35
  • @Divakar I thought one reshape less would pay off. I think the reason is that sum is faster along first dimension, isn't it? Do you remember the reference for that?
    – Luis Mendo
    Sep 9, 2014 at 20:54
  • @LuisMendo Well my impression thus far has been that squeeze and permute aren't cheap, but reshape is. Regarding sum along dim3, I think I had one discussion with you that if we could avoid squeeze that way, then it's worth it. Does that ring any bell? :)
    – Divakar
    Sep 9, 2014 at 20:58
2

I don't see what's going to be more straightforward and concise than

E = A(:,1:7) + A(:,8:14) + A(:,15:21)

Unless you need an expression that generalizes in some way you're not describing...

1
  • You are right, my problem description was somewhat sloppy. Nevertheless, Divakar got what I was driving at!
    – rookieMI
    Sep 9, 2014 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.