2013-02-27 3 views
3

각각의 열에서 임의의 값을 얻기 다음과 같이 W :matlab에 : 나는 2 차원 매트릭스를/O를 제로

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 

난에 0이 아닌있는 값에서 임의의 숫자를 얻기 위해 모든 열에서 필요한 벡터. 값 5는 항상 존재하므로 모두 0 인 열이 없습니다. 벡터에서 작업을 사용하여이 작업을 수행하는 방법에 대한 아이디어가 있습니다 (각 열을 별도로 처리하지 않고). 예 결과가 될 것이다 [1 1 1 1 5]

감사

+0

'randi' (http://www.mathworks.com/help/matlab/ref/randi.html) 함수가 다른 범위의 정수 벡터를 허용하지 않기 때문에 사용자 정의 함수 없이는 어려울 수 있다고 생각합니다. –

+0

프로젝트를 git에 업로드했습니다 : https://github.com/guywald/allele_fixation –

답변

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))'); 
+0

'[nonZeroIndices, ~] = find (possibleDirections); 구문에 대해 설명 하시겠습니까? 나는 전에 이것을 본 적이 없다 ... – Floris

+0

@Floris [I, J] = find (X, ...)는 선형 인덱스 대신에 행과 열 인덱스를 X에 반환한다. 열의 인덱스를 파기한다). 덕분에 – grantnz

+0

. 매일 새로운 것을 배우십시오! – Floris

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); 
+0

: _) 감사합니다. 매력처럼 작동합니다! –

2

다른 해결책 :

[r,c] = size(possibleDirections); 

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

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

매트릭스 possibleDirections의 요소는 항상 문제에 주어진 예와 같은 각각의 행 수와 동일 0이거나하는 경우에는, 마지막 줄 필요는 없다 해결책은 이미 idx 일 것입니다.

그리고 (오히려 재미) 한 줄 : possibleDirections의 값이 1e5보다 훨씬 작은 경우

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

참고하지만,이 한 줄에만 작동합니다.

+1

당신은 첫 번째 어둠을 따라'최대'를 취해야합니까? 'max (..., [], 1)'? – Shai

+0

기본값은'max'입니까? –

+2

@Shai, @HMuster 당신이 맞습니다. 'dim' 인수를 사용하면 1 행 행렬을 얻는 경우에 더 안전합니다. – yuk