3

我有一个二维矩阵如下:

possibleDirections =

 1     1     1     1     0
 0     0     2     2     0
 3     3     0     0     0
 0     4     0     4     4
 5     5     5     5     5

我需要从每一列中从向量中的非零值中获取一个随机数。值 5 将始终存在,因此不会有任何列全为零。任何想法如何通过使用向量上的操作来实现这一点(不单独处理每一列)?一个示例结果是 [1 1 1 1 5]

谢谢

4

3 回答 3

2

您可以在不直接循环或通过 arrayfun 循环的情况下执行此操作。

[rowCount,colCount] = size(possibleDirections);
nonZeroCount = sum(possibleDirections ~= 0);
index = round(rand(1,colCount) .* nonZeroCount +0.5);
[nonZeroIndices,~] = find(possibleDirections);
index(2:end) = index(2:end) + cumsum(nonZeroCount(1:end-1));
result = possibleDirections(nonZeroIndices(index)+(0:rowCount:(rowCount*colCount-1))');
于 2013-02-27T20:12:46.217 回答
2

替代解决方案:

[r,c] = size(possibleDirections);

[notUsed, idx] = max(rand(r, c).*(possibleDirections>0), [], 1);

val = possibleDirections(idx+(0:c-1)*r);

如果矩阵possibleDirections中的元素始终为零或等于问题中给出的示例中的相应行号,则不需要最后一行,因为解决方案已经是idx.

还有一个(相当有趣的)单行:

result = imag(max(1e05+rand(size(possibleDirections)).*(possibleDirections>0) + 1i*possibleDirections, [], 1));

但是请注意,这种单线仅在possibleDirections中的值远小于时才有效1e5

于 2013-02-27T20:56:31.323 回答
1

arrayfun通过两个调用尝试此代码:

nc = size(possibleDirections,2); %# number of columns
idx = possibleDirections ~=0;    %# non-zero values
%# indices of non-zero values for each column (cell array)
tmp = arrayfun(@(x)find(idx(:,x)),1:nc,'UniformOutput',0); 
s = sum(idx); %# number of non-zeros in each column
%# for each column get random index and extract the value
result = arrayfun(@(x) tmp{x}(randi(s(x),1)), 1:nc); 
于 2013-02-27T19:35:22.090 回答