有没有办法生成一个矩阵,其中每个元素定义为10 + row_index + column_index而没有for循环?

Ric*_*ano 3 matlab matrix

我正在尝试生成一个矩阵,其中每个元素定义为10*row_index + column_index.行和列可以波动到9x9矩阵.例如:

11    12    13    14    15    16
21    22    23    24    25    26
31    32    33    34    35    36
41    42    43    44    45    46
51    52    53    54    55    56
Run Code Online (Sandbox Code Playgroud)

使用for循环算法非常简单,但我已经被警告过,for除非绝对必要,否则在处理矩阵时应该避免循环,因为它们比向量/矩阵运算慢.

在Matlab 2012b中有哪些其他方法可以生成这样的矩阵?

Jon*_*nas 6

对于您的特定矩阵,它非常简单:

nRows = 4;
nCols = 5;

out = bsxfun(@plus,10*(1:nRows)',1:nCols)

out =

11    12    13    14    15
21    22    23    24    25
31    32    33    34    35
41    42    43    44    45
Run Code Online (Sandbox Code Playgroud)

  • @Ricardoaltamirano:在最新版本的Maltab中,for循环并不总是较慢,但在这种情况下,我认为你不能击败`bsxfun`. (2认同)