开发者

MATLAB: pre-allocation of matrix yields error

开发者 https://www.devze.com 2022-12-21 11:42 出处:网络
I\'m writing a simple MATLAB program to solve a project Euler problem. The program creates a 900 x 900 matrix. Before creation of this matrix c by the program, I pre-allocate it in the following way

I'm writing a simple MATLAB program to solve a project Euler problem.

The program creates a 900 x 900 matrix. Before creation of this matrix c by the program, I pre-allocate it in the following way:

c = zeros(900,900);

This yields an orange error message: "The value assigned to variable 'c' might be unused".

Later 开发者_开发百科in the program the matrix c is filled with numbers. So why the error message?


This is an mlint WARNING message. Not truly an error. An error will prevent your code from running. The mlint warnings merely suggest an inefficiency, a point where your code was possibly not efficiently written.

There is no need to preallocate an array that will then be reallocated. In fact, your first assignment is useless here. Later on in your code you then defined c as the result of a product of two vectors. As such, matlab completely ignores what you did in the first step. So that statement was indeed wasted and therefore should be dropped.

In general, only preallocate an array where you will later on assign only individual elements (or small groups of elements) of that array, perhaps in a loop.


When you say 'orange error message' do you mean the message is in the MATLAB editor? This is an output from M-Lint, which attempts to catch common coding "mistakes" that obey the syntax of the language but might be errors. How is c getting filled with numbers? If you have something like

c = zeros(900,900);
....stuff happens...
c = myfunction();

then MATLAB will reallocate c even if myfunction returns a 900x900 matrix. Have you scanned through the code to make sure that c isn't getting overwritten or replaced after the initial declaration? I've seen M-Lint screw up sometimes, but not often.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号