# Min of each column of a sparse matrix?

3 ビュー (過去 30 日間)
Elvira123 2018 年 2 月 13 日

How can I compute the min of each column of a sparse matrix excluding empty cells? I'm trying with: MIN = min(MATRIX, [], 1);
But the results is a column vector of zeros.
Thank you Elvira

サインインしてコメントする。

### 回答 (3 件)

Paras Gupta 2022 年 6 月 28 日
Hi,
The ‘min’ function generally works for full matrices (or dense matrices) only. In the case of sparse matrices, the ‘min’ function would consider the missing zero elements thereby giving the result as 0.
The following code illustrates how a vector with the minimum of each column can be computed in the case of sparse matrices.
% MATRIX is the given sparse matrix
% First, we use the find the row and column indices for non-zero elements
[ii,jj] = find(MATRIX);
% MIN is the vector with min of each column
% We use the accumarray function to apply the @min function on the selected
% index groups jj
MIN = accumarray(jj,nonzeros(MATRIX),[],@min)
You can refer to the documentation on sparse matrices, find, nonzeros, and accumarray for more information to understand how the above code works. A different method as proposed in the following answer can also be referred to compute the desired result. https://in.mathworks.com/matlabcentral/answers/35309-max-min-of-sparse-matrices
Hope this helps!
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Matt J 2022 年 6 月 28 日

result = -log( max( spfun(@(x)exp(-x), yourMatrix) ,[],1) );
##### 0 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Jan 2022 年 6 月 28 日

For large inputs a loop is faster than accumarray:
X = sprand(2000, 20000, 0.2);
tic;
for k = 1:10
[ii,jj] = find(X);
MIN = accumarray(jj, nonzeros(X), [], @min);
end
toc
Elapsed time is 1.261082 seconds.
tic;
for k = 1:10
MIN2 = myMin(X);
end
toc
Elapsed time is 1.008365 seconds.
isequal(MIN, MIN2.')
ans = logical
1
function M = myMin(X);
[i1, i2, v] = find(X);
M = Inf(1, size(X, 2));
for k = 1:numel(v)
if M(i2(k)) > v(k)
M(i2(k)) = v(k);
end
end
end

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by