poster
2019-12-10, 20:48
accumarray() (http://www.mathworks.com/help/techdoc/ref/accumarray.html)的val参数必须是向量。在我的情况下,我需要对矩阵的各列进行求和(或平均)。有功能或方法可以实现这一目标吗?
我现在在做的是在for循环中,我分别对列值求和:
for iCol = 1:nCols means(:,iCol) = accumarray(labels', X(:,iCol)); end
回答:
一种解决方案是在labels复制行索引,并添加另一列的列索引。然后,您可以将X重塑为列向量,并一次应用accumarray (https://www.mathworks.com/help/matlab/ref/accumarray.html) :
labels = [repmat(labels(:),nCols,1) ... % Replicate the row indices kron(1:nCols,ones(1,numel(labels))).']; % Create column indices totals = accumarray(labels,X(:)); % I used "totals" instead of "means"
怎么运行的...
列向量subs和向量val A = accumarray(subs,val)通过将val(i)中的数字与输出列向量A中的行subs(i)的总数相加来工作。然而, subs可以包含的不仅仅是行索引更多。它可以包含多个维度的下标索引,以在输出中分配值。这个功能就是让你来处理输入val这是一个矩阵,而不是一个向量。
首先,可以使用冒号运算符 (https://www.mathworks.com/help/matlab/ref/colon.html) X(:)将val的输入重塑为列向量。接着,为了跟踪哪些列中的输出中的值X(:)应放置,我们可以通过修改输入subs到包括额外的列索引。为了说明其工作原理,我将使用以下示例输入:
labels = [3; 1; 1]; X = [1 2 3; ... 4 5 6; ... 7 8 9]; nCols = 3 这是上面代码中的变量最终看起来像什么:
labels = 3 1 X(:) = 1 totals = 11 13 15 1 1 4 0 0 0 1 1 7 1 2 3 3 2 2 1 2 5 1 2 8 3 3 3 1 3 6 1 3 9 例如,请注意,最初在X的第一列中的值1 4 7将仅在输出的第一列中累积,如labels第二列的前三行中的值所示。结果输出应该与使用问题中的代码循环遍历每一列以执行累加所得到的结果相同。
更多&回答... (https://stackoverflow.com/questions/4350735)
我现在在做的是在for循环中,我分别对列值求和:
for iCol = 1:nCols means(:,iCol) = accumarray(labels', X(:,iCol)); end
回答:
一种解决方案是在labels复制行索引,并添加另一列的列索引。然后,您可以将X重塑为列向量,并一次应用accumarray (https://www.mathworks.com/help/matlab/ref/accumarray.html) :
labels = [repmat(labels(:),nCols,1) ... % Replicate the row indices kron(1:nCols,ones(1,numel(labels))).']; % Create column indices totals = accumarray(labels,X(:)); % I used "totals" instead of "means"
怎么运行的...
列向量subs和向量val A = accumarray(subs,val)通过将val(i)中的数字与输出列向量A中的行subs(i)的总数相加来工作。然而, subs可以包含的不仅仅是行索引更多。它可以包含多个维度的下标索引,以在输出中分配值。这个功能就是让你来处理输入val这是一个矩阵,而不是一个向量。
首先,可以使用冒号运算符 (https://www.mathworks.com/help/matlab/ref/colon.html) X(:)将val的输入重塑为列向量。接着,为了跟踪哪些列中的输出中的值X(:)应放置,我们可以通过修改输入subs到包括额外的列索引。为了说明其工作原理,我将使用以下示例输入:
labels = [3; 1; 1]; X = [1 2 3; ... 4 5 6; ... 7 8 9]; nCols = 3 这是上面代码中的变量最终看起来像什么:
labels = 3 1 X(:) = 1 totals = 11 13 15 1 1 4 0 0 0 1 1 7 1 2 3 3 2 2 1 2 5 1 2 8 3 3 3 1 3 6 1 3 9 例如,请注意,最初在X的第一列中的值1 4 7将仅在输出的第一列中累积,如labels第二列的前三行中的值所示。结果输出应该与使用问题中的代码循环遍历每一列以执行累加所得到的结果相同。
更多&回答... (https://stackoverflow.com/questions/4350735)