优化从MATLAB矩阵提取数据? [英] Optimizing extraction of data from a MATLAB matrix?

查看:107
本文介绍了优化从MATLAB矩阵提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个n维值矩阵:通过任意索引(即坐标)检索值的最有效方法是什么?

Given an n-dimensional matrix of values: what is the most efficient way of retrieving values by arbitrary indices (i.e. coordinates)?

例如在一个随机的5x5矩阵中,如果我想要(1,1)(2,3)和(4,5)处的值,最有效的方法就是只返回这些坐标处的值?

E.g. in a random 5x5 matrix, if I want the values at (1,1) (2,3) and (4,5) what is the most efficient way of returning just the values at these coordinates?

例如,如果我在单独的矩阵中提供这些坐标,则是否只有一行 MATLAB 哪个可以做?像这样:

If I provide these coordinates in a separate matrix for example is there a one line of MATLAB which can do the job? Something like:

    x=rand(5,5);

    y=[[1,1];[2,3];[4,5]];

    z=x(y);

除非那行不通.

但是请注意,由于各种原因,我无法使用线性索引-必须使用原始索引返回结果.而且这些矩阵的大小可能非常大,因此我也不想使用循环.

One caveat however, for various reasons I am unable to use linear indexing - the results must be returned using the original indices. And the size of these matrices is potentially very large so I don't want to use loops either.

推荐答案

如果您反对使用线性索引和循环,则唯一的替代选择AFAIK是逻辑索引.但是,如果y始终采用您建议的形式,则需要根据y中指定的索引创建逻辑矩阵.

If you're against using linear indexing and loops, the only other alternative, AFAIK, is logical indexing. But if y always comes in the form you've suggested, you'll need to create a logical matrix from the indices specified in y.

您能解释一下为什么不允许线性索引吗?

Could you explain why linear indexing is not allowed?

无论如何,如果您想要一个真正愚蠢的答案(这就是我所能提供的全部信息):

Anyway, if you want a really stupid answer (which is all I can provide with this much information):

z = diag(x(y(:,1),y(:,2)))

当然,这将不必要地创建一个巨大的矩阵并从中提取对角元素(您需要的对角元素),但它只需一行就可以完成,等等.

Of course, this will needlessly create a huge matrix and extract the diagonal elements (the ones you need) from it - but it gets it done in one line, etc.

:如果限制是对原始数据使用线性索引,则可以使用线性索引来创建逻辑矩阵并以此为索引x.例如

If the restriction is using linear indexing on the original data, then you can use linear indexing to create a logical matrix and index x with that. E.g.

% Each element of L is only one byte
L = false(size(x)); 
% Create the logical mask
L(sub2ind(size(x),y(:,1),y(:,2))) = true;
% Extract the required elements
z = x(L);

类似地,对于3维矩阵:

Similarly, for a 3-dimensional matrix:

x = rand(3,3,3);
y = [1 1 1;2 2 2;3 3 3];
L = false(size(x));
L(sub2ind(size(x),y(:,1),y(:,2),y(:,3))) = true;
z = x(L);

此外,逻辑索引应该比线性索引要快,因此除了构建蒙版之外,您的状态还不错.

Also, logical indexing is supposed to be faster than linear indexing, so apart from building the mask, you're in good shape.

这篇关于优化从MATLAB矩阵提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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