MATLAB: Wondering about the efficiency of the code or if there is a better way to do what I am trying to do

helpMATLABprojectquestion

For this problem the objective was:
Write a function that receives matrix A (e.g. 4×4 integer matrix) and returns the matrix B and value b. The value b should be the sum of all matrix elements of matrix A. For matrix B and value b the following two rules should be followed: • The matrix B should have only the second and third rows of matrix A; unless matrix A has less than 3 rows; in this case,an error message (”Err1: Matrix Size Incompatible”) should be returned for B and b should be -1. • The matrix B should have only the fist and second columns of matrix A, unless matrix A has less than 2 columns; in this case, an error message (”Err1: Matrix Size Incompatible”) should be returned for B and b should be -1.
My code is the following, and I am just wondering if there is a better way to go about doing what I did here either more efficiently or just more clearly?
function [B,b] = shrink(A)
% function to shrink A down to a 2×2 integer and return the sum as value b
B = A;
% sets B array equal to A.
[rowsInB, columnsInB] = size(B);
% finds number of rows and columns in B
msg1 = 'Err1: Matrix Size Incompatible';
% defines a msg for errors given later
if rowsInB < 3
% defines a case if the rows is less than 3 to return error message
% and value of -1 for b
b = -1;
B = msg1;
return
else
%if first case is not met, remove the 1st row of the array
B(1,:) = [];
end
[rowsInB,~] = size(B);
% gets new row size
for rows = 3:rowsInB
% deletes any rows past 2
B(rowsInB,:) = [];
[rowsInB,~] = size(B);
end
if columnsInB < 2
% defines a case if the columns is less than 2 to return error message
% and value of -1 for b
b = -1;
B = msg1;
return
end
[~,columnsInB] = size(B);
% gets new column size for B
for columns = 3:columnsInB
B(:,columnsInB) = [];
[~,columnsInB] = size(B);
end
b = sum(A,'all');
% gets the sum of all elements in the original array
end

Best Answer

generally, deleting columns (esp. one-by-one) is less efficient than indexing. Assuming all of the tests have passed, you can simply build B as the 2nd-3rd row and 1st-2nd column of A like this:
B = A(2:3,1:2);