how can i avoid the for loop in this case?

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 12 May 2020
Edited: Stephen23 on 12 May 2020
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!