MATLAB: Matrix containing values of another matrix at specific indices

六眼飞鱼酱① 提交于 2019-12-12 01:39:49

问题


I need help solving an indexing problem. The assigned problem states: Two matrices (x and y) give the coordinates to form matrix B from matrix A. Produce the matrix B which contains the values of A at the given coordinates in x and y. For instance:

x = [1 1 1; 2 2 1]
y = [1 2 1; 3 2 4]
%This would read as (1,1),(1,2),(1,1),(2,3),(2,2),(1,4)
% Given matrix: 
A = [6 7 8 9; 10 11 12 13];
%This would give us this answer for B (using the coordinate scheme above): 
B=[6 7 6; 12 11 9];

I'm guessing I need to use the find function in conjunction with a sub2ind function, but I'm not 100% sure how to translate that into working code. The only thing I can think of would be to do something like this:

B=((x(1),(y(1)), (x(2),y(2)).......

But that would only work for the defined matrix above, not a randomly generated matrix. I tried looking for a similar problem on the site, but I couldn't find one. Your help would be really appreciated!


回答1:


You can't do it for randomly generated matrices, because you have to ensure that matrix A has lines and columns as required from the values of x and y.

In this case, you can write:

for i=1:length(x(:))
   B(i)=A(x(i),y(i));
end
B=reshape(B,size(x));


来源:https://stackoverflow.com/questions/17516031/matlab-matrix-containing-values-of-another-matrix-at-specific-indices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!