Skip to main content
 首页 » 编程设计

python之在 matlab 中稀疏核/相似矩阵

2025年05月04日9wayfarer

我正在做一些内核 PCA 并想稀疏矩阵。我在 Python 中完成了所有工作,现在想将我的代码转换为 matlab 以进行比较。

我在想要稀疏化核矩阵的时候有点挣扎。在 Python 中,这对我来说非常简单。这是一个简单矩阵的示例,向您展示我的意思:

import numpy as np 
print('Sparsify a matrix by zeroing all elements but the top 2 values in a row.\n') 
 
A = np.array([[1,2,3,4,5],[9,8,6,4,5],[3,1,7,8,9]]) 
 
print('Before:\n%s\n' %A) 
 
for row in A: 
    sort_idx = np.argsort(row)[::-1] # get indexes of sort order (high to low) 
    for i in sort_idx[2:]: 
        row[i]=0 
 
print('After:\n%s\n' %A) 


Sparsify a matrix by zeroing all elements but the top 2 values in a row. 
 
Before: 
[[1 2 3 4 5] 
 [9 8 6 4 5] 
 [3 1 7 8 9]] 
 
After: 
[[0 0 0 4 5] 
 [9 8 0 0 0] 
 [0 0 0 8 9]] 

那么,我将如何在 matlab 中执行此操作?

如果你能在这里帮助我,那就太好了。是否有等效于 argsort 的方法,即连续获取例如 3 个最低值以便我可以将它们设置为 0?

请您参考如下方法:

一种方法-

[m,n] = size(A); %// get size 
[~,col_ind]= sort(A,2,'descend') %// sort the rows in descending order 
A(bsxfun(@plus,(col_ind(:,3:end)-1)*m,[1:m]'))=0 %// get all indices other than  
             %// for top 2 values in each row and set those in A to zero 

请记住,使用这种方法,将保留第一个匹配的最大值和第二个最大值。

sample 运行-

A (Before) = 
     1     2     3     4     5 
     9     8     6     4     5 
     3     1     7     8     9 
     5     6     2     6     7 
 
A (After) = 
     0     0     0     4     5 
     9     8     0     0     0 
     0     0     0     8     9 
     0     6     0     0     7