Borrar filtros
Borrar filtros

how can i avoid the for loop in this case?

2 visualizaciones (últimos 30 días)
Dror Aizik
Dror Aizik el 12 de Mayo de 2020
Comentada: Dror Aizik el 12 de Mayo de 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

Respuesta aceptada

Stephen23
Stephen23 el 12 de Mayo de 2020
Editada: Stephen23 el 12 de Mayo de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by