How to print the sum of the middle array's columns ?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
dpb
el 20 de Jul. de 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)
Respuestas (1)
Varun
el 1 de Sept. de 2023
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
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!