Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
利用matlab高效填充稀疏矩阵_Matlab_Sparse Matrix - Fatal编程技术网

利用matlab高效填充稀疏矩阵

利用matlab高效填充稀疏矩阵,matlab,sparse-matrix,Matlab,Sparse Matrix,我正在使用一个非常大的稀疏矩阵: U = sparse(a,b) % a and b are very large 另一方面,存在具有“a”行的单元格Ind。在每一行中,存在一个“变量”数量的元素,例如: Ind{1} = [1 3 5 19 1000 1340] Ind{2} = [9 100 1500 1600 8000 b] ... Ind{a} = [3 5 6 90 1000 4300 5712 9480] 可以看出,Ind{i}中的最大索引数可以是'b

我正在使用一个非常大的稀疏矩阵:

  U = sparse(a,b)   % a and b are very large
另一方面,存在具有“a”行的单元格Ind。在每一行中,存在一个“变量”数量的元素,例如:

  Ind{1} = [1 3 5 19 1000 1340]
  Ind{2} = [9 100 1500 1600 8000 b]
    ...
  Ind{a} = [3 5 6 90 1000 4300 5712 9480]
可以看出,Ind{i}中的最大索引数可以是'b'。对于这些索引向量中的每一个,也存在一个类似“c”的内容矩阵:

 c = [2 3 1 6 3 5 1 3 4 1 2 ... 5]   
问题是,对于Ind{i}中的每个元素,我想用c(Ind{i})填充'row=i'和'col=Ind{i}',即


问题是“a”非常大,循环需要很长时间才能计算。有没有办法避免循环

我不确定是否有办法避免循环,但通过构建三个大向量(两个用于行和列索引,一个用于值)并在循环后构建稀疏矩阵,我确实获得了2到20的速度提升系数(我将
a
的范围从3到5000,
b
固定为10000):

strides = cellfun(@numel,Ind);
n       = sum(strides);
I(n,1)  = 0;
J(n,1)  = 0;
S(n,1)  = 0;
bot     = 1;

for k = 1:a
    top  = bot + strides(k) - 1 ;
    mask = bot:top              ;
    %
    I(mask) = k         ;
    J(mask) = Ind{k}    ;
    S(mask) = c(Ind{k}) ;
    %
    bot = top + 1;
end
U = sparse(I,J,S,a,b);

这是建议使用的
sparse
,因为稀疏矩阵的赋值比常规数组更昂贵。

U=sparse(I,J,S,a,b)非常有趣。只剩下一个小问题:假设J=[50 300 12 9 50 12]。如果我们想使列数等于max(J),那是胡说八道。在本例中,J需要是:J=[3 4 2 1 3 2]。如果J非常大,在你看来,什么函数可以进行这种转换?@YAS“如果我们想使列数等于max(J)”,我一点也不明白。
sparse
的最后一个参数定义了稀疏矩阵的最大列数。@TroyHaskin次要注释。你可以只做
strips=cellfun(@numel,Ind)。不需要用
numel
包装匿名函数,因为您可以直接调用
numel
d。@rayryeng-Huh。我不知道这两种形式之间有什么区别。不,没有。。。少打字:)这是我心中的密码。
strides = cellfun(@numel,Ind);
n       = sum(strides);
I(n,1)  = 0;
J(n,1)  = 0;
S(n,1)  = 0;
bot     = 1;

for k = 1:a
    top  = bot + strides(k) - 1 ;
    mask = bot:top              ;
    %
    I(mask) = k         ;
    J(mask) = Ind{k}    ;
    S(mask) = c(Ind{k}) ;
    %
    bot = top + 1;
end
U = sparse(I,J,S,a,b);