Effacer les filtres
Effacer les filtres

find the longest diagonal sum of a matrix.

1 vue (au cours des 30 derniers jours)
Thomas
Thomas le 30 Oct 2023
function largestDiagonalSum = diag_sum(matrix)
[rows,cols] = size(matrix);
largestDiagonalSum = 0;
for row = 1:rows
for col = 1:cols
diagonalSum = 0;
for dr = [-1, -1, 1, 1]
for dc = [-1, 1, -1, 1]
r = row + dr;
c = col + dc;
if r >= 1 && r <= rows && c >= 1 && c <= cols
diagonalSum = diagonalSum + matrix(r, c);
end
end
end
if diagonalSum > largestDiagonalSum
largestDiagonalSum = diagonalSum;
end
end
end
% Divide the largest diagonal sum by 4
largestDiagonalSum = largestDiagonalSum / 4;
end
im not too woried aboout my code as it has to be just good eniugh to get me throiugh this semester of uni, though i keep getting ther erro
>> diag_sum
Not enough input arguments.
Error in diag_sum (line 2)
[rows, cols] = size(matrix);

Réponses (2)

Walter Roberson
Walter Roberson le 30 Oct 2023
When you press the green Run button, that is equivalent to running the function from the command line with no parameters.
When you run a function and do not pass parameters to it, then inside the function, any variable named on the function line remains undefined (unless you assign it a value.)
Under no circumstances will MATLAB go hunting around in the calling environment trying to find a variable named in the function line to use the value of inside the function.

Image Analyst
Image Analyst le 30 Oct 2023
Assign something to matrix first, like
m = magic(5)
then call your function
largestDiagonalSum = diag_sum(m)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by