通过向量迭代

时间:2014-03-29 07:45:00

标签: matlab indexing

我写了这个(columnrowvalue是向量):

for k = column
    for l = row ((column == k) & (row > k))
        A_lk = value (row == l & column == k);

问题在于kl是向量,所以我无法写row == lcolumn == k(我想要那些i row (i)lcolumn (i)k)。

确切的错误是:" mx_el_eq: nonconformant arguments (op1 is 46x1, op2 is 13x1)"。

如何逐个使用列和行((column == k) & (row > k))中的所有元素?

我想到了类似的东西:

for i = 1:length(column)
    k = column (i)

还有其他可能吗?

修改

正如我所说,我有一个稀疏矩阵(n,n)。我必须迭代所有列和每列(比如说k)我必须遍历从k + 1到n的行,并用非零元素做一些事情。

示例:

row    = [1 3 3 2 1 2]      % row > 2 is [0 1 1 0 0 0] 
column = [1 1 2 2 2 3]  % column == 2 is [0 0 1 1 1 0]  
value  = [8 7 9 5 6 7]  %(column == 2) & (row > 2) is [0 0 1 0 0 0] 

row ((column == 2) & (row > 2))是3
value (row == 3 & column == 2)是9

我想要代码做什么:

k in {1, 2, 3}  %writing this I realized I did some useless operations, 
                %since I want just the distinct values of column
k = 1:  
    l in row ((column == 1) & (row > 1)) = {3}  
        l = 3:
            A_31 = value (row == 3 & column == 1) = 7
            %rest of the code
k = 2:
    l in row ((column == 2) & (row > 2)) = {3}
        l = 3
            A_32 = value (row == 3 & column == 2) = 9
            %rest of the code
k = 3:
    l in row ((column == 3) & (row > 3)) = nothing

2 个答案:

答案 0 :(得分:1)

在下面的代码中查看match_value的值,看看是否可以使用它们 -

row    = [1 3 3 2 1 2]      % row > 2 is [0 1 1 0 0 0] 
column = [1 1 2 2 2 3]  % column == 2 is [0 0 1 1 1 0]
value  = [8 7 9 5 6 7]

k_vector = 1:numel(column)
match_ind = bsxfun(@gt,row,k_vector') & bsxfun(@eq,column,k_vector')
match_value = bsxfun(@times,match_ind,value)

match_value

的输出
match_value =

     0     7     0     0     0     0
     0     0     9     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0
     0     0     0     0     0     0

如果你打算使用稀疏输出,你可以很容易地这样做 -

>> sparse(match_value)

ans =

   (1,2)        7
   (2,3)        9 

答案 1 :(得分:1)

unique的帮助下迭代列很简单 - 我们可以轻松地拉出每列下三角部分的非零元素,如下所示:

% this relies on 'row' and 'column' both being row vectors
for c = unique(column)
    colidx = (column == c);
    lowertri = (row > c) & colidx;
    v = value(lowertri);
    % do something with v
end

如果v元素的行索引也很重要(而不是仅仅迭代值本身),要么并行使用row(row>c),要么只在行中有一个内循环与列相同的方式。