紧凑的MATLAB矩阵索引表示法 [英] Compact MATLAB matrix indexing notation

查看:459
本文介绍了紧凑的MATLAB矩阵索引表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个n-by-k大小的矩阵,每行包含k个数字。我想使用这些k数作为k维矩阵的索引。在MATLAB中是否有任何紧凑的方法,或者我必须使用for循环?

I've got an n-by-k sized matrix, containing k numbers per row. I want to use these k numbers as indexes into a k-dimensional matrix. Is there any compact way of doing so in MATLAB or must I use a for loop?

这是我想要做的(在MATLAB伪代码中),但是在更多MATLAB-ish方式:

This is what I want to do (in MATLAB pseudo code), but in a more MATLAB-ish way:

for row=1:1:n
    finalTable(row) = kDimensionalMatrix(indexmatrix(row, 1),...
          indexmatrix(row, 2),...,indexmatrix(row, k))
end


推荐答案

如果你想避免使用for循环,这可能是最干净的方法:

If you want to avoid having to use a for loop, this is probably the cleanest way to do it:

indexCell = num2cell(indexmatrix, 1);
linearIndexMatrix = sub2ind(size(kDimensionalMatrix), indexCell{:});
finalTable = kDimensionalMatrix(linearIndexMatrix);

第一行是每列 indexmatrix 使用 num2cell 。这允许我们将所有 k 列作为逗号分隔列表 sub2ind ,将下标索引(行,列等)转换为线性索引的函数(每个矩阵元素的编号从1到 N N 是矩阵中元素的总数)。最后一行使用这些线性索引来替换for循环。可以找到关于矩阵索引(下标,线性和逻辑)的一个很好的讨论这里

The first line puts each column of indexmatrix into separate cells of a cell array using num2cell. This allows us to pass all k columns as a comma-separated list into sub2ind, a function that converts subscripted indices (row, column, etc.) into linear indices (each matrix element is numbered from 1 to N, N being the total number of elements in the matrix). The last line uses these linear indices to replace your for loop. A good discussion about matrix indexing (subscript, linear, and logical) can be found here.

回避的倾向来自for循环,支持向量化解决方案是许多MATLAB用户(包括我自己)已经习以为常的东西。但是,较新版本的MATLAB可以更有效地处理循环。正如对另一个问题的答案所讨论的那样,使用for循环有时会导致代码运行速度比运行速度快一个矢量化的解决方案。

The tendency to shy away from for loops in favor of vectorized solutions is something many MATLAB users (myself included) have become accustomed to. However, newer versions of MATLAB handle looping much more efficiently. As discussed in this answer to another SO question, using for loops can sometimes result in faster-running code than you would get with a vectorized solution.

我当然不是说你不应该再试图对代码进行矢量化,只是每个问题都是独一无二的。向量化通常效率更高,但总是。对于您的问题,for循环与矢量化代码的执行速度可能取决于值 n k 的大小是。

I'm certainly NOT saying you shouldn't try to vectorize your code anymore, only that every problem is unique. Vectorizing will often be more efficient, but not always. For your problem, the execution speed of for loops versus vectorized code will probably depend on how big the values n and k are.

这篇关于紧凑的MATLAB矩阵索引表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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