Matlab:从没有零的每列中获取随机值

Matlab:从没有零的每列中获取随机值,matlab,random,vector,matrix,zero,Matlab,Random,Vector,Matrix,Zero,我有一个二维矩阵,如下所示: 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将始终存在,因此不会有任何列全部为零。 你知道如何通过对向量进行运算(不单独处理每一列)来实现这一点

我有一个二维矩阵,如下所示:

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 5]


谢谢

请通过两次
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); 

您可以不直接循环或通过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))');
替代解决方案:

[r,c] = size(possibleDirections);

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

val = possibleDirections(idx+(0:c-1)*r);
如果矩阵
可能的方向
中的元素始终为零或等于问题中给出的示例中的相应行号,则不需要最后一行,因为解决方案已经是
idx

还有一句(相当有趣的)一句话:

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

但是,请注意,只有当
可能的指示
中的值远小于
1e5
时,此一行程序才起作用

我认为如果没有自定义函数,这可能会很困难,因为
randi
()函数不接受不同范围的整数向量。我已将该项目上载到git::)谢谢,非常有用!你能解释一下语法是什么吗是什么?我以前从未见过它…@Floris[I,J]=find(X,…)将行和列索引而不是线性索引返回到X。该~用于强制此模式(但放弃列索引)。don;您是否需要沿着第一个dim设置
max
max(…,[],1)
?这不是默认的
max
?@Shai,@HMuster你们都是对的。如果得到一行矩阵,使用
dim
参数更安全。@yuk好的,我添加了维度的显式规范。感谢您的建议(Shai)和澄清(yuk)。