我有一个方阵。我需要分析每个对角线并检查每个对角线中是否至少有n =阈值相邻元素大于0。如果相邻正元素的数量小于阈值,那么我必须将这些元素设置为0.
我刚刚写了两个函数。其中一个提取后续对角线,计算正元素并将对角线中的适当元素设置为0.第二个插入对角线改变为矩阵。
我已多次尝试更正此代码,但我仍遇到同样的问题。有人能帮助我吗?谢谢你的进步。
function [ filteredMatrix ] = filterMatrix2( matrix, threshold )
sum = 0; %counts adjacent numbers that are > 0
matrixDimension = length(matrix);
filteredMatrix = matrix;
%a diagonal number is in range [ -dimension+1 ; dimension-1 ]
for k = (-matrixDimension+1) : (matrixDimension-1)
diagonal = diag(matrix, k); %get next diagonal
diagonalLength = length(diagonal);
sum=0;
%if a diagonal length is shorter than threshold,
%than i must set all elements to 0
if ( diagonalLength < threshold )
diagonal = zeros(diagonalLength, 1);
else
for x = 1 : diagonalLength
if diagonal(x) > 0
sum = sum+1;
else
if ( sum < threshold )
%set previous elements to 0
for y = x-sum : x
diagonal(y) = 0;
end
sum = 0;
end
end
end
end
filteredMatrix = setDiagonal2(filteredMatrix, k, diagonal); (line 33)
end
end
第二功能:
function [ changedMatrix ] = setDiagonal2( matrix, numberOfDiagonal, diagonal )
changedMatrix = matrix;
diagonalLength = length(diagonal);
numberOfRows = size(matrix,1);
%numberOfColumns = size(matrix,2);
%determin index of the first element of the diagonal
if numberOfDiagonal < 0
firstIndex = 1 - numberOfDiagonal;
else
firstIndex = 1 + numberOfDiagonal*numberOfRows;
end
changedMatrix(firstIndex : numberOfRows+1 : diagonalLength) = diagonal;
(line 15)
end
这是一个问题:
在作业A(:) = B中,A和B中的元素数必须相同。
setDiagonal2(第15行)错误
changedMatrix(firstIndex:numberOfRows + 1:diagonalLength)=对角线;
filterMatrix2中的错误(第33行)
filteredMatrix = setDiagonal2(filteredMatrix,k,diagonal);