紧凑的 MATLAB 矩阵索引符号 [英] Compact MATLAB matrix indexing notation

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

问题描述

我有一个 n×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 的方式:

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);

第一行使用 num2cell.这允许我们将所有 k 列作为 以逗号分隔的列表sub2ind,一个将下标索引(行、列等)转换为线性索引的函数(每个矩阵元素编号从1到NN 是矩阵中元素的总数).最后一行使用这些线性索引来替换您的 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.

许多 MATLAB 用户(包括我自己)已经习惯了避免使用 for 循环而支持矢量化解决方案的趋势.但是,较新版本的 MATLAB 处理循环的效率更高.正如在另一个 SO 问题的这个答案中所讨论的那样,使用 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 循环与向量化代码的执行速度可能取决于 nk 的值有多大.

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天全站免登陆