user30609
user30609

Reputation: 264

Summing matrices in matlab (with a twist)

I have a matrix H, which for arguments sake is of size 6-by-6.

I need to sum three things, first I need h_ii, then I need to sum all the other elements which contain element i, apart from h_ii. Then I need all the other that do not contain j.

To visualise this, have created the following diagram,

enter image description here

So from the diagram,

For each diagonal of the matrix, h11, h22, ... , h66.

I need to sum the orange (cells that contain all the ij cells), and then the yellow, (the cells that do not contain i, the jj cells).

I have tried to sum the individual columns and rows but this becomes very messy.

Ideally, I need to give the matrix, and it produces h11 = X, h11_orange = Y, and h11_yellow = Z.

Upvotes: 2

Views: 87

Answers (2)

rahnema1
rahnema1

Reputation: 15837

You can use this vectorized version:

green = diag(H);
orange = sum(H,1).' + sum(H,2) - 2* green;
yellow = sum(H(:)) - orange - green;

Upvotes: 4

Adriaan
Adriaan

Reputation: 18177

h=magic(6);
out = zeros(size(h,1),size(h,2),3);  % Initialise output
out(:,:,1) = h;  % Copy the green

for ii = 1:size(h,1)
    for jj = 1:size(h,2)
        % out(ii,jj,1) = h(ii,jj);  % Green bit
        % For orange, sum the row and column. Note the .' transpose,
        % otherwise implicit broadcasting on the plus will create a matrix.
        % Finally remove the green cell twice,
        % as you added it in both row and column
        out(ii,jj,2) = sum(h(ii,:)+h(:,jj).') - h(ii,jj)*2;
        % Sum everything for yellow, and subtract the orange and green
        out(ii,jj,3) = sum(h,'all') - out(ii,jj,2) - h(ii,jj)
    end
end

This will make a 3D output matrix, i.e. it's of the same size as the input matrix with 3 pages for your green, orange and yellow parts. See the comments in the code for what does what.

Thanks flawr for your comment on improving speed on the yellow summation.

Upvotes: 3

Related Questions