필터 지우기
필터 지우기

how can i avoid the for loop in this case?

조회 수: 2 (최근 30일)
Dror Aizik
Dror Aizik 2020년 5월 12일
댓글: Dror Aizik 2020년 5월 12일
a_matrix=zeros(10,4);
a=[3 6 7 8]';
for i=1:numel(a)
a_matrix(a(i),i)=1;
end
disp(a_matrix)
0 0 0 0
0 0 0 0
1 0 0 0
0 0 0 0
0 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0
0 0 0 0

채택된 답변

Stephen23
Stephen23 2020년 5월 12일
편집: Stephen23 2020년 5월 12일
Method one: logical equals:
>> a = [3,6,7,8];
>> V = 1:10;
>> M = double(V(:)==a) % requires MATLAB >= R2016b
M =
0 0 0 0
0 0 0 0
1 0 0 0
0 0 0 0
0 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0
0 0 0 0
For earlier MATLAB versions replace == with bsxfun.
Method two: sub2ind:
>> M = zeros(10,4);
>> X = sub2ind(size(M),a,1:4);
>> M(X) = 1
M =
0 0 0 0
0 0 0 0
1 0 0 0
0 0 0 0
0 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0
0 0 0 0

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by