Wondering about the efficiency of my code or if there is a better way to do what I am trying to do?
Show older comments
For this problem the objective was:
Write a function that receives matrix A (e.g. 4x4 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 2x2 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
Accepted Answer
More Answers (0)
Categories
Find more on Linear Prediction in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!