Take a 4x1 and 4x2 matrix and create a 4x2 matrix instead of a 4x4

3 visualizaciones (últimos 30 días)
I have the following data that I am trying to put into an array, but I am not finding the right combination of bracketing to make this work:
% state_rotate is fixed to these values of 4x2 double array
state_rotate=[1,3;1,3;2,4;2,4];
% state_indx gets set in other parts of the code; it can be 1;1;1;1 to 2;2;2;2 only using 1 or 2 as digits
state_indx = [1;2;2;1];
% take and using state_index (1 or 2 value) which state "wins"
win_state(1)=state_rotate(1,state_indx(1));
win_state(2)=state_rotate(2,state_indx(2));
win_state(3)=state_rotate(3,state_indx(3));
win_state(4)=state_rotate(4,state_indx(4));
For this example the end result is
win_state = [1;3;4;2]
What i would like to do is use a more compact notation to assign values to win_state. Something along the lines of:
win_state=state_rotate(:,state_indx(:));
This notation gives me a 4x4 matrix with what appears to be the correct values diagonally. I would like to not use a for loop but do the right type of matrix calculations.
I am still learning matlab, and it seemed maybe reshape could help, but I don't want to create the larger matrix since if I scale this code this matrix can get rather large.
Thanks!

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 30 de Abr. de 2020
Here is the compact notation using sub2ind()
state_rotate=[1,3;1,3;2,4;2,4];
state_indx = [1;2;2;1];
idx = sub2ind(size(state_rotate), 1:size(state_rotate,1), state_indx.');
win_state = state_rotate(idx);
  2 comentarios
charles purwin
charles purwin el 2 de Mayo de 2020
Thank you, didn't know about this function. Exactly what I needed! Read the function, literally designed for my need!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by