Search code examples
matrixoctavediagonalmatrix-indexingsubmatrix

How to obtain an entry of a square matrix inside a non square matrix


I am trying to print the last element of the largest square sub-matrix of some arbitrary-shaped rectangular matrix. I have several hints for this task:

Set the variable y to be the last diagonal entry of A. Since A may not be square, you will need to determine whether the last diagonal entry of A is $a_{mm}$ or $a_{nn}$.

Set the variable B to be the (square) matrix containing either the first m columns of A (if m is less than n), or the first n rows of A otherwise.

I've tried doing different combinations of m (columns) and n (rows) such as A(1:m/n,:), A(:,1:m/n).

I've also tried combining the two concepts above using codes such as X(m/n:m/,1/m/n:m/n).

I'm a bit confused on how to just print the last square entry as all those combinations either result in an error (some rows are larger than columns therefore invalid, and vice versa) or it printed out the last value of the matrix, not a square matrix.

The expected result is supposed to give me the last value in a square matrix of a non-square matrix.

For example, if a matrix is

$[2,3,4,6;0,1,-1,-10]$

I expect the output to be 1, but I get -10, or errors.


Solution

  • Here are several approaches:

    A = [2,3,4,6;0,1,-1,-10];          % Define A
    [m,n] = size(A);                   % Get the size of A
    B = A ( 1:min(n,m), 1:min(n,m) );  % Get the sub array B
    d = diag(B);                       % Obtain the diagonal of B
    lastEntry = d(end);                % Obtain the last entry of the diagonal
    

    In MATLAB, the following also works (skipping the creation of B):

    A = [2,3,4,6;0,1,-1,-10];          % Define A
    d = diag(A);                       % Obtain the diagonal of A
    lastEntry = d(end);                % Obtain the last entry of the diagonal
    

    Or this:

    A = [2,3,4,6;0,1,-1,-10];             % Define A
    [m,n] = size(A);                      % Get the size of A
    lastEntry = A ( min(n,m), min(n,m) ); % Access the relevant element