如果存在未知数量的非零和零,解决问题的一种方法是首先用 NaN 替换零,然后使用 max 或 min 之类的东西来查找数据。
%# create an array
M = [-0.6 1.8 -2.3 0 0 0; 0 0 0 3.4 -3.8 -4.3; -0.6 0 0 3.4 0 0];
%# replace zeros with NaN
M(M==0) = NaN;
%# get, for each column, the number
numbers = max(M,[],1)
numbers =
-0.6000 1.8000 -2.3000 3.4000 -3.8000 -4.3000
编辑
这就是我理解这个问题的方式:“我希望对于每一列都知道非零条目的值。每列只有一个非零数字,但它可能会出现多次”
这是一种更类似于 Matlab(但更长)的方法来获得解决方案:
%# create an array
M = [-0.6 1.8 -2.3 0 0 0; 0 0 0 3.4 -3.8 -4.3; -0.6 0 0 3.4 0 0];
%# find the non-zero entries
[r,c] = find(M);
%# only take one entry per column
[uniqueCols, sortIdx] = unique(c);
%# fix the rows correspondingly
uniqueRows = r(sortIdx);
%# convert to index
idx = sub2ind(size(M),uniqueRows,uniqueCols);
%# get the numbers per column (transpose as needed)
numbers = M(idx)
numbers =
-0.6000
1.8000
-2.3000
3.4000
-3.8000
-4.3000