Matlab矩阵索引来自2个数组(X,Y) [英] Matlab matrix indexing from 2 Arrays (X,Y)

查看:246
本文介绍了Matlab矩阵索引来自2个数组(X,Y)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型数组的X和Y位置,我想用它们来定义该位置的内容.我可以运行for循环来定义位置,但我认为会有更快的方法.我尝试使用数组位置定义函数.

I have X and Y positions for a large array and I would like to use them to define what the contents of that position. I could run a for loop to define the positions but I think there would be a faster method. I tried to use the array position define function.

x = [6,2,3]
y = [1,2,3]

c = [1,1,1,2,2,3;...
     1,1,1,2,2,5;...
     2,2,1,4,2,3;...
     1,1,4,3,2,3;...
     1,2,3,4,5,3;...
     1,2,3,5,4,2];

当我在上面输入方程式时,它会在下面给出答案

When I type the equation above it results in the answer below

c(y,x)
ans =
 1     2     3
 1     1     1
 2     2     1

我要寻找的是数组中1:1的位置.

What I'm looking for are the 1:1 positions from the arrays.

c(y(1),x(1))
c(y(2),x(2))
c(y(3),x(3))

有什么方法可以将数组限制为线性序列吗?我现在唯一的猜测是将数组重塑为包含单个a和b的单元格矩阵,然后执行一次cellfun.但我想我把它变得复杂了.

Is there any way to limit the arrays to a linear sequence? my only guess right now is to reshape the arrays into a cell matrix containing the individual a and b and then perform a cellfun. but I think I'm making it to complicated.

推荐答案

您必须先将位置转换为线性索引,然后才能按所需的线性顺序获取正确的元素.您可以使用 sub2ind 来帮助您做到这一点:

You have to convert the locations into linear indices first, then you can grab the correct elements in the desired linear sequence. You can use sub2ind to help you do that:

ind = sub2ind(size(c), y, x); % Get linear indices
v = c(ind); % Get the elements

这样做可以得到:

>> v = c(ind)

v =

     3     1     1

您可以亲自验证每对(y,x)是否都为您提供了所需的正确元素.例如,当y = 1x = 6时,检索到的元素为3,依此类推.

You can verify for yourself that each pair of (y,x) gives you the right element you're looking for. For example, when y = 1 and x = 6, the element retrieved is 3 and so on.

这篇关于Matlab矩阵索引来自2个数组(X,Y)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆