Create a matrix using the following code:
A = [1, 5, 2; 3, 6, 4];
A = 1 5 2 3 6 4
end keyword is frequently used in conjunction with the colon operator (i.e.
:). Once you understand how they work, you can build concise indexing expressions.
% Element at the last row, second column of A target = A(end,2);
target = 6
% Elements in the last row lastRow = A(end,:);
lastRow = 3 6 4
% Elements in the penultimate column penultimateCol = A(:,end-1);
penultimateCol = 5 6
% Last element lastElement = A(end);
lastElement = 4
% Elements whose linear index is an odd number atOddIdxs = A(1:2:end);
atOddIdxs = 1 5 2
% Elements in reverse order reverse = A(end:-1:1);
reverse = 4 2 6 5 3 1
You can use
end in statements that grow a matrix, although in these cases the matrix must already exist.
% Add a new column and set values to -1 A(:,end+1) = -1;
A = 1 5 2 -1 3 6 4 -1
I recommend the following books to learn more on matrix manipulation in MATLAB:
This book was the winner of a 2017 Textbook Excellence Award. The second chapter explains the colon operator, linear indexing, and subscript indexing.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The fourth chapter is completely dedicated to matrix manipulation.
I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.
- Subscript Indexing in MATLAB
- How MATLAB Stores Matrices in Memory
- Linear Indexing in MATLAB
- How to Convert Linear Indices to Subscripts and Viceversa in MATLAB
- MATLAB end Keyword in Matrix Indexing Expressions
- Logical Indexing in MATLAB
- A Deeper Look on Logical Indexing in MATLAB
- MATLAB Colon Operator in Matrix Indexing Expressions
A student who did not know how to use the
end keyword, wrote the following code to calculate the sum of certain elements in a two-dimensional matrix
X of a size greater than or equal to 2×2.
[rowsCount,colsCount] = size(X); sum1 = X(1,1) + X(1,colsCount); sum2 = X(2,1) + X(rowsCount,colsCount); sum3 = sum(X(rowsCount-1,:)); sum4 = sum(X(rowsCount,2:2:colsCount)); sum5 = sum(X(:,colsCount)) + sum(X(rowsCount-1,:)) + X(rowsCount,colsCount);
Refactor the code using the
end keyword. Check that the original code and the refactored code yield the same result.
A possible solution could be:
sum1_r = X(1) + X(1,end); sum2_r = X(2) + X(end); sum3_r = sum(X(end-1,:)); sum4_r = sum(X(end,2:2:end)); sum5_r = sum(X(:,end)) + sum(X(end-1,:)) + X(end); sum1_ok = (sum1 == sum1_r); sum2_ok = (sum2 == sum2_r); sum3_ok = (sum3 == sum3_r); sum4_ok = (sum4 == sum4_r); sum5_ok = (sum5 == sum5_r);
I hope you have learned how to use the
end keyword in MATLAB. It is a powerful tool to build concise indexing expressions. The source code developed in this tutorial is available at this page.