由于您明确希望将已删除的全零行和列恢复到其原始位置,因此这里有一个解决方案正是这样做的。基本上,我存储全零行和列的行和列索引。然后,使用这些索引进行删除本身。之后,我恢复了与之前删除的一样多的全零行和列,并将它们放在原始数据的“末尾”。最后,我确定了正确的“置换向量”来重新排列所有行和列。 (也许,笔和纸对于遵循线性代数很有用。)
代码如下:
% Set up test data.
data = 10 * rand(5);
data(data < 8) = 0
% Save original data for later comparison.
dataOrig = data;
% Find row and column indices off all-zero rows/columns.
rowIdx = find(all(~data, 2)).'
colIdx = find(all(~data, 1))
nRows = numel(rowIdx);
nCols = numel(colIdx);
% Remove all-zero rows/columns.
data(rowIdx, :) = [];
data(:, colIdx) = []
%%% Here goes your own function only working on the "cleaned" data.
% data = yourFunction(data)
% Restore all-zero rows/columns "at the end".
[rows, cols] = size(data);
data = [data; zeros(nRows, cols)];
data = [data, zeros(rows+nRows, nCols)];
% Restore original row and column order.
[rows, cols] = size(data);
permRow([rowIdx, setdiff(1:rows, rowIdx)]) = [(rows-nRows+1):rows, 1:(rows-nRows)]
permCol([colIdx, setdiff(1:cols, colIdx)]) = [(cols-nCols+1):cols, 1:(cols-nCols)]
data = data(permRow, permCol)
% Comparison
all(dataOrig(:) == data(:))
还有,运行的输出:
data =
0.0000 0.0000 8.9283 0.0000 8.6185
0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.0000 0.0000 8.2942 0.0000
0.0000 8.0730 0.0000 0.0000 8.6491
rowIdx =
2 3
colIdx =
1
data =
0.0000 8.9283 0.0000 8.6185
0.0000 0.0000 8.2942 0.0000
8.0730 0.0000 0.0000 8.6491
permRow =
1 4 5 2 3
permCol =
5 1 2 3 4
data =
0.0000 0.0000 8.9283 0.0000 8.6185
0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.0000 0.0000 8.2942 0.0000
0.0000 8.0730 0.0000 0.0000 8.6491
ans =
1
希望有帮助!