Filter löschen
Filter löschen

how can i avoid the for loop in this case?

2 Ansichten (letzte 30 Tage)
Dror Aizik
Dror Aizik am 12 Mai 2020
Kommentiert: Dror Aizik am 12 Mai 2020
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

Akzeptierte Antwort

Stephen23
Stephen23 am 12 Mai 2020
Bearbeitet: Stephen23 am 12 Mai 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by