简体   繁体   English

矩阵如何存储在Matlab / Octave中?

[英]How are matrices stored in Matlab/Octave?

Short version 简洁版本

If I have matrix like this: 如果我有这样的矩阵:

1  2
3  4

In memory, is it stored as [1 2 3 4] or as [1 3 2 4] . 在内存中,它以[1 2 3 4][1 3 2 4] In other words, are matrices more optimized for row or for column access ? 换句话说,矩阵是针对 访问还是针对列访问 进行更优化


Long version 长版

I'm translating some code from Matlab to NumPy. 我正在将一些代码从Matlab转换为NumPy。 I'm used to C convention for multidimensional arrays (ie last index veries most rapidly, matrices are stored by rows) which is default for NumPy arrays . 我习惯于多维数组的C约定(即,最后一个索引的查询速度最快,矩阵按行存储),这是NumPy数组的默认设置 However, in Matlab code I see snippets like this all the time (for arrangement several colored images in a single multidimensional array): 但是,在Matlab代码中,我一直看到这样的代码片段(将多个彩色图像排列在一个多维数组中):

images(:, :, :, i) = im

which looks suboptimal for C convention and more optimized for FORTRAN convention (first index veries most rapidly, matrices are stored by columns). 对于C约定,它看起来不是最佳选择,而对于FORTRAN约定,它则进行了优化(第一个索引的查询速度最快,矩阵按列存储)。 So, is it correct that Matlab uses this second style and is better optimized for column operations? 那么,Matlab使用第二种样式并针对列操作进行了更好的优化是否正确?

Short answer: It is stored column-wise. 简短答案:它按列存储。

A = [1 2; 3 4];
A(:) = [1; 3; 2; 4];

In many cases, the performance can be much better if you do the calculations in the "correct order", and operate on full columns, and not rows. 在许多情况下,如果按照“正确顺序”进行计算,并且对整列而不是行进行运算,则性能可能会好得多。

A quick example: 一个简单的例子:

%% Columns
a = rand(n);
b = zeros(n,1);
tic
for ii = 1:n
  b = b + a(:,ii);
end
toc
Elapsed time is 0.252358 seconds.

%% Rows:
a = rand(n);
b = zeros(1,n);
tic
for ii = 1:n
  b = b + a(ii,:);
end
toc
Elapsed time is 2.593381 seconds.

More than 10 times as fast when working on columns! 在色谱柱上工作的速度快十倍以上!

%% Columns
n = 4000;

a = rand(n);
b = zeros(n,1);
tic
for j = 1 : 10
 for ii = 1:n
  b = b + a(:,ii);
 end
end
toc


%% Rows new:
a = rand(n);
b = zeros(1,n);
tic
for j = 1 : 10
 for ii = 1:n
  b = b + a(ii);
 end
end
toc

%% Rows old:
a = rand(n);
b = zeros(1,n);
tic
for j = 1 : 10
 for ii = 1:n
  b = b + a(ii,:);
 end
end
toc

Results: 结果:

Elapsed time is 1.53509 seconds. 经过的时间是1.53509秒。

Elapsed time is 1.03306 seconds. 经过的时间是1.03306秒。

Elapsed time is 3.4732 seconds. 经过的时间是3.4732秒。

So it looks like working on rows is SLIGHTLY faster than working on column, but using : causes the slowdown. 因此,似乎处理行比处理列稍快,但是使用会导致速度变慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM