【问题标题】:use vector to select columns of a matlab array [duplicate]使用向量选择matlab数组的列[重复]
【发布时间】:2014-10-21 15:35:00
【问题描述】:

这是我经常发现自己试图解决的问题。我有以下内容:

A = [1 2;
     3 4;
     5 6;
     7 8;
     9 10];

B = [1,2,1,2,2];

在 A 的每一行 (i) 上,我想返回 B(i) 中指定的列的值。我目前使用循环解决问题:

result = zeros(size(B));
for i=1:length(B)
    result(i) = A(i,B(i));
end

结果 = [1 4 5 8 10]

但这对我来说似乎很不雅。有单行吗?

【问题讨论】:

    标签: matlab matrix indexing


    【解决方案1】:

    您可以使用sub2ind 获得正确的线性索引:

    rows = (1:numel(B))'
    cols = B(:);
    ind = sub2ind(size(A), rows, cols);
    A(ind)
    

    或单线

    A(sub2ind(size(A), (1:numel(B))', B(:)))
    

    或者更优雅的方法(取自2nd answer to the duplicate question

    diag(A(:,B))
    

    不过我不能告诉你性能...

    【讨论】:

    • 这些中哪些可以推广到 n 维数组?
    • 您能否更具体地说明 n-D 问题是什么样的?
    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多