matlab code function pre allocations

Status
Not open for further replies.

kimo4ever

Member level 2
Joined
Dec 10, 2010
Messages
45
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,286
Activity points
1,574
hello, i am asking about the meaning of putting [ ] in the code ?..for ex, mod=[ ], ? thnx
 

A declaration like that defines the variable as a) existing, and b) being empty.

(Disappointingly, the following lame example of bad programming practice is the best that springs to mind
Let's say you have a loop in which a variable dynamically grows with each iteration*. For example:

for i=1:10
a = [a i^2];
end

(This will build a row vector of squares).

If you try to run this as is, MATLAB will fail with a warning
??? Undefined function or variable 'a'.

Preallocating a = []; will fix the issue.

MATLAB's help also offers a few more useful applications of the [] assignment:
"A = [ ] stores an empty matrix in A. A(m, = [ ] deletes row m of A. A,n) = [ ] deletes column n of A. A = [ ] reshapes A into a column vector and deletes the nth element."


* MATLAB's M-lint tool will warn you about this sort of code being slow, as the array 'a' must be resized with each loop iteration.
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…