find the longest diagonal sum of a matrix.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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);
0 Kommentare
Antworten (2)
Walter Roberson
am 30 Okt. 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.
0 Kommentare
Image Analyst
am 30 Okt. 2023
Assign something to matrix first, like
m = magic(5)
then call your function
largestDiagonalSum = diag_sum(m)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!