MATLAB:包含在特定索引处的另一个矩阵的值的矩阵 [英] MATLAB: Matrix containing values of another matrix at specific indices
问题描述
我需要帮助解决索引问题.分配的问题状态:两个矩阵(x和y)给出坐标以从矩阵A形成矩阵B.产生矩阵B,该矩阵B在x和y中的给定坐标下包含A的值. 例如:
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];
我猜想我需要结合使用find
函数和sub2ind
函数,但是我不确定100%如何将其转换为工作代码.我唯一能想到的就是做这样的事情:
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!
推荐答案
您不能对随机生成的矩阵执行此操作,因为必须确保矩阵A
具有y
.
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));
这篇关于MATLAB:包含在特定索引处的另一个矩阵的值的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!