MATLAB中如何将一个矩阵每一列的最小非零元素变成零?

2024-12-03 22:23:23
推荐回答(1个)
回答1:

实现题目所要求功能的MATLAB代码如下:


[m n] = size(A);  % mxn矩阵
i = 1;
i_record = [];
Ai_record = [];
j = 1;

while j<=n  % 逐列检查
while i<=m
if A(i,j)~=0
i_record = [i_record, i];  % 记录下标
Ai_record = [Ai_record, A(i,j)];  % 记录值
end
i = i+1;
end
if length(i_record)>2
[value, i20_index] = min(Ai_record);
A(i_record(i20_index), j) = 0;
end
j = j+1;
i = 1;
i_record = [];
Ai_record = [];
end


输入示例A = [1 2 4; 0 3 0; 0 1 2]; 运行结果如下:

图  代码运行结果