%% Two lecture 2 problem 24.10.18
% 
% File Lprobl_boundaries.m
%%
format compact
%% Perimeter sum
%{
Using MATLAB indexing, compute the perimeter sum of the
matrix “magic(8)”.
Perimeter sum adds together the elements that are in the first and
last rows and columns of the matrix. Try to make your code
independent of the matrix dimensions using end.
You can do it at least in 2 ways of thought:
1. Pick the rows and parts of the columns that exclude the corner
points, and use sum suitably.
2. Embed a zero-matrix of size n − 2 × n − 2 inside magic(n)
(n=8) to produce, say Abd. Then do the summation either
sum(sum(...)) or sum(Abd(:))
Answer: 910
%}
%% Solution 1: Pick the boundaries.
A=magic(8)
sum(A(1,:))+sum(A(end,:))+sum(A(2:end-1,1))+sum(A(2:end-1,end))
%% Solution 2.: Fill the inner part A(2:end-1,2:end-1) with zeros

AA=A;   % Make a copy (just in case...)
AA(2:end-1,2:end-1)=zeros(6,6)  % All but boundarie to 0.
colsums=sum(AA)                 % Sum of columns, see the inner zeros.
perimetersum=sum(colsums)

%% Next exercise (Skip or not, let's NOT skip):
%{
- 1. Use reshape to form the matrix A:

     1     2     3     4
     5     6     7     8
     9    10    11    12
Hint: start with a 4 × 3-matrix and transpose it.
- 2. Find the size [m,n] of A (pretend, you just forgot it.)
- 3. Embed A into a zero-matrix AA of size (m + 2) × (n + 2)
- 4. Replace the first row of AA by [1, 2, . . . n + 2] and the last
row with [n + 2, n + 1, . . . 1].Hint: step -1, or fliplr
- 5. replace the m “inner entries (zeros)” (2,...,end-1) of the
first column of AA by -1’s
%}

%% Solution
%
%% 1-2.
A=reshape(1:12,4,3)'
[m,n]=size(A)        
%% 3. Run 1 command at the time, to see what's going on
AA=zeros(m+2,n+2)    % To be filled with M as inner part...
                     %  and boundaries with the given ones.
AA(2:end-1,2:end-1)=A
%% Boundaries:
AA(1,:)=1:n+2
%%
AA(end,:)=n+2:-1:1
%%
AA(2:end-1,1)=-1   % Scalar extension works even here.



