对于每一行,以矢量化方式重塑和计算特征向量

时间:2014-12-11 11:50:46

标签: octave

我一直想要解决这个问题很长一段时间,但还没有成功。我假设我将使用 arrayfun ,但我还没想到它。感谢帮助。这是问题所在:

给定一个包含许多行和N ^ 2列的矩阵,将每一行重新整形为NxN矩阵并计算特征值,并以不使用for循环的矢量化方式执行此操作。例如

A= 
0.6060168   0.8340029   0.0064574   0.7133187
0.6325375   0.0919912   0.5692567   0.7432627
0.8292699   0.5136958   0.4171895   0.2530783
0.7966113   0.1975865   0.6687064   0.3226548
0.0163615   0.2123476   0.9868179   0.1478827

for every **i**

m=reshape(A(i,:),2,2)

[vc vl]=eig(m)

我倾向于做类似

的事情
f = @(x) eig(reshape(x,2,2))

arrayfun(f,A)

但当然我收到了像

这样的错误
octave:5> arrayfun(f,A)
error: reshape: can't reshape 1x1 array to 2x2 array
error: evaluating argument list element number 1
error: evaluating argument list element number 1
error: called from:
error:    at line -1, column -1
error: cellfun: too many output arguments
error:   /usr/share/octave/3.2.4/m/general/arrayfun.m at line 168, column 21

2 个答案:

答案 0 :(得分:2)

A = [0.6060168 0.8340029 0.0064574 0.7133187;
0.6325375 0.0919912 0.5692567 0.7432627;
0.8292699 0.5136958 0.4171895 0.2530783;
0.7966113 0.1975865 0.6687064 0.3226548;
0.0163615 0.2123476 0.9868179 0.1478827];

N = 2;
[mc, ml] = arrayfun (@(row) eig (reshape (A (row, :), N, N)), 1:rows(A), "UniformOutput", false)

mc = 
{
  [1,1] =

    -0.170783  -0.044626
     0.985309  -0.999004

  [1,2] =

    -0.95343  -0.89053
     0.30161  -0.45492

  (cropped)

}
ml = 
{
  [1,1] =

Diagonal Matrix

     0.56876         0
           0   0.75057

  [1,2] =

Diagonal Matrix

     0.45246         0
           0   0.92334
(cropped)

答案 1 :(得分:1)

使用Ndpar package,可以在多个核心上并行化计算。 借用安迪的回答,

pkg load ndpar

A = [0.6060168 0.8340029 0.0064574 0.7133187;
0.6325375 0.0919912 0.5692567 0.7432627;
0.8292699 0.5136958 0.4171895 0.2530783;
0.7966113 0.1975865 0.6687064 0.3226548;
0.0163615 0.2123476 0.9868179 0.1478827];

N = 2;
[eigenvectors, eigenvalues] = ndpar_arrayfun(nproc, 
                                @(row) eig(reshape(row, N, N)), 
                                A, "IdxDimensions", 1, "Uniformoutput", false)

产生相同的输出。


编辑 - 或使用octave-forge pararrayfun包中的原始parallel

[eigenvectors, eigenvalues] = pararrayfun(nproc, 
                                @(row_idx) eig(reshape(A(row_idx, :), N, N)), 
                                1:rows(A), "UniformOutput", false)