find the longest diagonal sum of a matrix.

1 次查看(过去 30 天)
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);

回答(2 个)

Walter Roberson
Walter Roberson 2023-10-30
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 2023-10-30
Assign something to matrix first, like
m = magic(5)
then call your function
largestDiagonalSum = diag_sum(m)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by