如果存在未知数量的非零和零,解决该问题的一种方法是首先用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
@niko:我建议你更清楚地解释您的具体目标是什么,因为你可以质疑不同的解释。我想知道我是否需要开始道歉。 – Jonas 2010-04-15 15:01:20