简体   繁体   English

使用Matlab在线性时间内将矩阵放入稀疏形式

[英]Putting a matrix in to sparse form in linear time using matlab

I'm trying to put a matrix in sparse form, and so far I'm looping through the rows and columns checking every element to see if it's non zero. 我正在尝试以稀疏形式放置矩阵,到目前为止,我正在遍历行和列,检查每个元素以查看其是否为非零。 However, this seems to be order n^2, where n is the number of non zero elements in the matrix. 但是,这似乎是n ^ 2阶,其中n是矩阵中非零元素的数量。 Is there a way to do this order n? 有没有办法执行此命令n?

Here is my code 这是我的代码

function a = inputMatrix(X)




[m,n] = size(X);


k=1;
for i=1:m


   for j=1:n


       if X(i,j)~=0
           X(i,j);




           a(1,k) = struct('row',i,'column',j,'data',X(i,j));




           k = k+1;




       end




   end


end

Here is my time testing 这是我的时间测试

ri = zeros(250,250);
rj = zeros(250,250);
rk = zeros(100,100);








for i=1:10000
    ri(i) = randi([-10000,10000],1,1);
end
tic;
inputMatrix(ri);
time(1) = toc;




for i=1:5000
    rj(i) = randi([-10000,10000],1,1);
end


tic;
inputMatrix(rj);
time(2) = toc;








for i=1:1000
    rk(i) = randi([-10000,10000],1,1);
end


tic;
inputMatrix(rj);
time(3) = toc;

Results: 结果:

time = 1.8009 0.5619 0.5545 no. 时间= 1.8009 0.5619 0.5545号 non zero entires = 10 000, 5000, 1000 非零整数= 10000,5000,1000

The results suggest there is a non linear relationship, and not order N 结果表明存在非线性关系,而不是N阶

find为您提供非零元素的索引, sparse将矩阵直接转换为稀疏矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM