tags:

views:

112

answers:

2

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?

+3  A: 

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.

mtrw
Thanks for your reply mtrw.Yes, the error is indeed an M-lint error. I should have worded my question differently: the matrix c is the result of the multiplication of a column- and a row vector. Do you think pre-allocation is optimal in this case? If yes, then why the M-lint error?Pieter
Pieter
You can go back and edit your original question. That will improve the question even for people that do not end up reading all the comments.
MatlabDoug
+6  A: 

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.

woodchips
Thanks Peter, very clear.
Pieter

related questions