2014-07-18 4 views
0

weightmat이라고하는 0의 m 행렬이 있습니다.다른 행렬에 인덱스로 행렬 요소 사용

placeIn이라는 고유 한 임의의 정수의 m 행 k 행렬을 가지고 있습니다. 여기에서 k는 <이고 가장 큰 요소는 placeIn이고 < = n입니다.

해당 값을 행 인덱스로 사용하여 placeIn의 요소를 weightmat에 배치하려고합니다. placeIn의 특정 행에 4가 들어있는 경우 해당 행의 4 번째 열에 4를 넣으려고합니다 (weightmat). 여기에 내가 말하는 것을 수행하는 예제 코드가 있습니다.

% create placeIn 

placeIn = []; 
for pIx = 1:5 
    placeIn = [placeIn; randperm(9,3)]; 
end 

display(placeIn) 

weightmat = zeros(5,10); 

for pIx = 1:5 
    for qIx = 1:3 
     weightmat(pIx,placeIn(pIx,qIx)) = placeIn(pIx,qIx); 
    end 
end 

display(weightmat) 

벡터화 된 방법이 있습니까? for 루프를 중첩하지 않고이 작업을 수행하고 싶습니다.

답변

3

비결은 sub2ind입니다 :

% First generate the row indices used for the indexing. We'll ignore the column. 
[r c] = meshgrid(1:size(placeIn, 2), 1:size(placeIn,1)); 

weightmat = zeros(5,10); 

% Now generate an index for each (c, placeIn) pair, and set the corresponding 
% element of weightmat to that value of placeIn 
weightmat(sub2ind(size(weightmat), c, placeIn)) = placeIn; 
관련 문제