如何存储是在Matlab /八度矩阵? [英] How are matrices stored in Matlab/Octave?

查看:141
本文介绍了如何存储是在Matlab /八度矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的矩阵:

1  2
3  4

在内存中,它存储为 [1 2 3 4] [1 3 2 4] 。换句话说,是矩阵的更优化作为列访问

In memory, is it stored as [1 2 3 4] or as [1 3 2 4]. In other words, are matrices more optimized for row or for column access?

我翻译一些code从MATLAB到numpy的。我已经习惯了C约定多维数组(即最后一个索引veries最为迅​​速,矩阵按行存储),这是<一个href=\"http://docs.scipy.org/doc/numpy/reference/internals.html#multidimensional-array-indexing-order-issues\"相对=nofollow>默认numpy的阵列的。然而,在Matlab code我看到这样的片断(在一个多维数组的安排几个彩色图像)所有的时间:

I'm translating some code from Matlab to NumPy. I'm used to C convention for multidimensional arrays (i.e. last index veries most rapidly, matrices are stored by rows) which is default for NumPy arrays. However, in Matlab code I see snippets like this all the time (for arrangement several colored images in a single multidimensional array):

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

这看起来次优C约定和FORTRAN约定(第一指标veries最为迅​​速,矩阵按列存储)更加优化。那么,是不是正确的,MATLAB的使用第二风格和列操作是更好地优化?

which looks suboptimal for C convention and more optimized for FORTRAN convention (first index veries most rapidly, matrices are stored by columns). So, is it correct that Matlab uses this second style and is better optimized for column operations?

推荐答案

简短的回答:这是存储列明智的。

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.

一个简单的例子:

%% 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.

10倍以上的速度在列上工作时!

More than 10 times as fast when working on columns!

这篇关于如何存储是在Matlab /八度矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆