Assignment and accessing using indices

I had a question about how to do a particular type of assignment using indices. The code below is a simplified example.
k = zeros(4,4);
v = [2,3];
k(v,v) = 1;
My intention was to get a result that looks like
ans =
[0, 0, 0, 0;
0, 1, 0, 0;
0, 0, 1, 0;
0, 0, 0, 0]
But unfortunately the result is:
ans =
[0, 0, 0, 0;
0, 1, 1, 0;
0, 1, 1, 0;
0, 0, 0, 0]
So my question is: Is there a way to access individual elements (rather than rectangular regions) without using a for loop (Which I understand is computationally expensive in MatLab)?

 Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 5 de Jun. de 2016
k = zeros(4,4);
v = [2,3];
idx=sub2ind(size(k),v,v)
k(idx) = 1;

1 comentario

Jeff Wood
Jeff Wood el 6 de Jun. de 2016
Thanks,
I should have mentioned that v might be different for rows and columns (i.e. I was using the generic case where they were the same).

Iniciar sesión para comentar.

Más respuestas (2)

Categorías

Etiquetas

Preguntada:

el 5 de Jun. de 2016

Comentada:

el 6 de Jun. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by