Take a 4x1 and 4x2 matrix and create a 4x2 matrix instead of a 4x4
3 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Ameer Hamza
2020-4-30
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);
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!