让z = [1 3 5 6]和通过获取每个元素之间的所有差异:我们得到:
bsxfun(@minus, z', z)
ans =
0 -2 -4 -5
2 0 -2 -3
4 2 0 -1
5 3 1 0现在我想按升序对这些值进行排序,并删除重复项。所以:
sort(reshape(bsxfun(@minus, z', z),1,16))
ans =
Columns 1 through 13
-5 -4 -3 -2 -2 -1 0 0 0 0 1 2 2
Columns 14 through 16
3 4 5
C = unique(sort(reshape(bsxfun(@minus, z', z),1,16)))
C =
-5 -4 -3 -2 -1 0 1 2 3 4 5但是通过查看[-5 -4 -3 -2 -1 0 1 2 3 4 5]中的-5,我怎么知道-5来自哪里呢?通过给自己读矩阵,
0 -2 -4 -5
2 0 -2 -3
4 2 0 -1
5 3 1 0我知道它来自z(1) - z(4),即第1行第4列。
此外,2来自z(3) - z(2)和z(2) - z(1),后者来自两个案例。在不读取原始矩阵本身的情况下,我们如何知道[-5 -4 -3 -2 -1 0 1 2 3 4 5]中的2最初位于原始矩阵的第3行第2列和第2行第1列?
因此,通过查看[-5 -4 -3 -2 -1 0 1 2 3 4 5]中的每个元素,我们如何知道,例如,-5在原始矩阵索引中的有效位置。我想知道,当我需要对-5和两个索引进行操作时,例如,对于每个差异,例如-5,我以z(1)- z(6) = -5的身份执行(-5)*1*6。但是对于第二个,我需要以z(3) - z(2) = 2的身份使用2*(3*2+2*1),z(2) - z(1) = 2不是唯一的。
仔细考虑,我认为我不应该将bsxfun(@minus, z', z)重塑为数组。我还将创建两个索引数组,以便可以有效地执行像上面所述的(-5)*1*6这样的操作。然而,这说起来容易做起来难,而且我还必须处理不明确的来源。或者我应该先做所需的操作?
发布于 2016-08-26 16:48:27
使用unique的第三个输出。不用排序,unique会帮你做的。
[sortedOutput,~,linearIndices] = unique(reshape(bsxfun(@minus, z', z),[1 16]))您可以从bsxfun重构结果,如下所示:
distances = reshape(sortedOutput(linearIndices),[4 4]);如果你想知道某个值出现在哪里,你可以这样写
targetValue = -5;
targetValueIdx = find(sortedOutput==targetValue);
linearIndexIntoDistances = find(targetValueIdx==linearIndices);
[row,col] = ind2sub([4 4],linearIndexIntoDistances);因为只要sortedOutput中的第一个值出现在原始向量中,linearIndices就是1。
发布于 2016-08-26 16:40:00
如果将bsxfun的结果保存在中间变量中:
distances=bsxfun(@minus, z', z)然后,您可以使用find迭代查找距离中的C值。
[rows,cols]=find(C(i)==distances)如果值重复,这将给出所有行和列。然后,您只需将它们用于您的方程式。
发布于 2016-08-26 19:10:04
您可以使用accumarray来收集与差异矩阵中的相同值对应的所有行和列索引:
z = [1 3 5 6]; % data vector
zd = bsxfun(@minus, z.', z); % matrix of differences
[C, ~, ind] = unique(zd); % unique values and indices
[rr, cc] = ndgrid(1:numel(z)); % template for row and col indices
f = @(x){x}; % anonymous function to collect row and col indices
row = accumarray(ind, rr(:), [], f); % group row indices according to ind
col = accumarray(ind, cc(:), [], f); % same for col indices例如,C(6)是值0,它在zd中由row{6}和col{6}指定的位置出现四次
>> row{6}.'
ans =
3 2 1 4
>> col{6}.'
ans =
3 2 1 4如您所见,不能保证对结果进行排序。如果需要按线性顺序对它们进行排序:
rowcol = cellfun(@(r,c)sortrows([r c]), row, col, 'UniformOutput', false);所以现在
>> rowcol{6}
ans =
1 1
2 2
3 3
4 4https://stackoverflow.com/questions/39161678
复制相似问题