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

1 次查看(过去 30 天)
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.
  3 个评论
Shuoze Xu
Shuoze Xu 2022-7-20
I think should use round() here, such as middle_column = round(cols/2)
dpb
dpb 2022-7-20
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)

请先登录,再进行评论。

回答(1 个)

Varun
Varun 2023-9-1
Hi,
I understand that you are trying to calculate the sum of middle column of a matrix (odd) without using “sum” function. You gave one solution where you have used 2 nested loops, time complexity is O(r*c).
You can achieve this task using single loop in time complexity O(r). Also, you can find the middle column index without using round. Refer the following code:
middle_column = (cols+1)/2;
middleColumnSum = 0;
for i = 1:rows
middleColumnSum = middleColumnSum + matrix(i, middle_column);
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by