フィルターのクリア

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
  1 件のコメント
Dror Aizik
Dror Aizik 2020 年 5 月 12 日
thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by