matlab矩阵太大内存,Matlab下大矩阵运算

通过memory和whos可以看到当前系统的内存使用情况和每个变量所占用的内存,例如:

K>> memory

Maximum possiblearray:               7414 MB (7.774e+009 bytes) *

Memory availableforall arrays:      7414 MB (7.774e+009 bytes) *

Memory used by MATLAB:                2433 MB (2.552e+009 bytes)

Physical Memory (RAM):                5823 MB (6.106e+009 bytes)

*  Limited by System Memory (physical + swapfile) available.

可以看到本地机器的物理内存RAM有将近6G,最大可能内存7G左右,目前已经被Matlab使用的内存有2G多,通过whos指令可以知道有那些变量占用的内存比较大:

K>> whos

Name                      Size                    Bytes  Class     Attributes

temp_instance_2       20229×10059            1627868088  double

temp_instance_3       20229×10059               2095424  double    sparse

train_data                1×10059              86199419struct

可以看到同样20139*10059的矩阵,double型的full矩阵要占用1.6G左右的内存,double型的sparse矩阵只占用了2M左右内存。

在运算速度方面 tic,toc来知道每段代码的执行时间。但要知道每条语句的详细运行情况的话,非profile莫属。先运行profile on,再运行需要测试的代码,然后使用profile viewer来查看报告。

Sparse矩阵在指定下标的循环运算中不占优势。但是,当一个矩阵中有大量的0时就一定要采用sparse型进行运算,不只大大减少内存会消耗,而且时间消耗也会大大减少。注意,一般Sparse矩阵运算如sum, diag等之后还是sparse矩阵,而当sparse矩阵和full矩阵一起参加运算时,结果会被强制转为full矩阵。要注意,当一个矩阵并不是很稀疏时尽量不要采用sparse方式存储,不便于矩阵运算,对于一些矩阵操作,如求矩阵转置等操作会变得异常异常的慢!

下面是一个2W*2W的double型全1矩阵full型和sparse型的占内存情况:

>> A = ones(20229,20229);

>> whos

Name          Size                    Bytes  Class     Attributes

A         20229×20229            3273699528  double

>> A = sparse(A);

>> whos

Name          Size                    Bytes  Class     Attributes

A         20229×20229            6547560896  double    sparse

在Matlab中一定要尽量避免矩阵的for循环元素,如果遇到一定是无法避免的情况是,考虑采用bsxfun来取代for,bsxfun的使用格式和范围有:

C = bsxfun(fun,A,B) appliesthe element-by-element binary operation specified by the function handle fun to arrays AandB,with singleton expansion enabled.fun can be one of the following built-infunctions:

@plus Plus

@minus Minus

@times Array multiply

@rdivide Rightarraydivide

@ldivide Leftarraydivide

@power Array power

@maxBinary maximum

@minBinary minimum

@rem Remainder after division

@mod Modulus after division

@atan2 Four quadrant inverse tangent

@hypot Square root ofsumof squares

@eq Equal

@ne Not equal

@lt Less than

@le Less thanorequal to

@gt Greater than

@ge Greater thanorequal to

@andElement-wise logical AND

@orElement-wise logical OR

@xor Logical exclusive OR