# How to print the sum of the middle array's columns ?

9 views (last 30 days)
Shuoze Xu on 19 Jul 2022
Commented: dpb on 20 Jul 2022
Here is an past exam question
a) read the dimensions of the matrix from the user and prompt the user for the data needed to fill the array (10 marks)
Sample Output:
How many rows?: 2How many columns?: 3
Enter the values for row 1, column 1: 5
Enter the values for row 1, column 2: 4
Enter the values for row 1, column 3: 6
Enter the values for row 2, column 1: 1
Enter the values for row 2, column 2: 2
Enter the values for row 2, column 3: 3
b) sum the elements of the middle column. The MATLAB function sum() must not be used in your solution (10 marks)
Sample Output: Given A = [ 5, 4, 6, 7, 3 ; 1, 2, 3, 4, 5 ; 5, 6, 4, 2, 4 ; 4, 5, 3, 2, 1]
The sum of all the elements of the middle column is: 16
Here is my code.
% (a)
% create two variables to store the number of rows and columns
numRow = input('How many rows?: ');
numCol = input('How many Cols?: ');
% create a variable as the empty vector
P = [];
for r = 1:numRow
for c = 1:numCol
fprintf('Enter the value for row %d column %d',r,c);
P(r,c) = input(': ');
end
end
% (b)
% ensure the number of row and col of P
[rows,cols] = size(P);
% create an variable sumMiddle
sumMiddle = 0;
for r = 1:rows
for c = 1:cols
if (mod(c,3) == 0)
sumMiddle = sumMiddle + P(r,c); % add all the elements together
end
end
end
fprintf('The sum of all the elements of the middle column is: %d ',sumMiddle);
The comment of the test result is that part 2 does not work properly. How can I improve the code of Part (b)?
Thank you.
dpb on 20 Jul 2022
Not best algebra/numerics, no...think some more...there's a direct way with no rounding required to compute the middle value (if total number of columns is odd, of course)

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!