MATLAB向量/一维数组的索引约定

3

考虑以下两个向量的预分配:

vecCol = NaN( 3, 1 );
vecRow = NaN( 1, 3 );

现在的目标是给这些向量赋值(例如,在循环中,如果无法进行矢量化)。关于索引,是否有惯例或最佳实践?以下方法是否推荐?
for k = 1:3
    vecCol( k, 1 ) = 1; % Row, Column
    vecRow( 1, k ) = 2; % Row, Column
end

还是按照以下方式编码更好吗?
for k = 1:3
    vecCol(k) = 1; % Element
    vecRow(k) = 2; % Element
end
2个回答

6

从功能上来说并没有什么区别。如果上下文表示向量始终是1D(您在此示例中的命名约定有所帮助),那么您可以仅使用vecCol(i)来简洁灵活地使用它。但是,使用vecCol(i,1)语法也有一些优点:

  • It's explicitly clear which type of vector you're using. This is good if it matters, e.g. when using linear algebra, but might be irrelevant if direction is arbitrary.
  • If you forget to initialise (bad but it happens) then it will ensure the direction is as expected
  • It's a good habit to get into so you don't forget when using 2D arrays
  • It appears to be slightly quicker. This will be negligible on small arrays but see the below benchmark for vectors with 10^8 elements, and a speed improvement of >10%.

    function benchie()
    % Benchmark. Set up large row/column vectors, time value assignment using timeit.
        n = 1e8;
        vecCol = NaN(n, 1); vecRow = NaN(1, n);
        f = @()fullidx(vecCol, vecRow, n);
        s = @()singleidx(vecCol, vecRow, n);
        timeit(f)
        timeit(s)
    end
    function fullidx(vecCol, vecRow, n)
    % 2D indexing, copied from the example in question
        for k = 1:n
            vecCol(k, 1) = 1; % Row, Column
            vecRow(1, k) = 2; % Row, Column
        end
    end
    function singleidx(vecCol, vecRow, n)
    % Element indexing, copied from the example in question
        for k = 1:n
            vecCol(k) = 1; % Element
            vecRow(k) = 2; % Element
        end
    end
    

    Output (tested on Windows 64-bit R2015b, your mileage may vary!)

    % f (full indexing):    2.4874 secs
    % s (element indexing): 2.8456 secs
    

    Iterating this benchmark over increasing n, we can produce the following plot for reference.

    enter image description here


4
在编程中,有一个普遍的经验法则是“显式优于隐式”。由于这两种方法之间没有功能上的区别,因此我认为它取决于上下文哪一种更清晰/更好:
  • 如果上下文使用了大量矩阵代数,并且行向量和列向量之间的区别很重要,则使用两个参数的索引来减少错误并方便阅读。

  • 如果上下文不太区分两者,而您只是将向量用作简单数组,则使用一个参数的索引会更加清晰。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接