Reputation: 11
In matlab, do I have to declare a matrix, and how do I do it? For example, can I do
function res = compute()
res(1) = 1;
res(2) = 2;
end
or do I have to declare res first?
Upvotes: 0
Views: 580
Reputation: 16450
You don't have to declare your matrices in matlab. Your code will work.
It is generally faster if you preallocate memory using ones
or zeros
for your matrices. Otherwise Matlab has to keep reallocating memory as the matrix changes size.
Example
% Slow
x(1) = 3; % x is now 1 by 1
x(5) = 9; % Matlab has to reallocate memory to increase x to be 1 by 5
x(10) = 2; % And another reallocation to increase x to be 1 by 10
% Better
y = zeros(1,10); % preallocate memory for the matrix
y(1) = 3;
y(5) = 9;
y(10) = 2;
% One-liner
z([1 5 10]) = [3 9 2]; % you can assign multiple values at once
Preallocation helps the most when you have to use loops
a = zeros(1,100)
for i=1:100
a(i) = i^2;
end
Even better if you can vectorize code so you don't have to use a for loop
a = (1:100).^2;
Upvotes: 2
Reputation: 23455
You don't have to declare the array/matrix. What you have right now will work.
You can always declare an empty matrix with matrix = []
Even crazier, you can do stuff like
a(2,3) = 7
resulting in
a =
0 0 0
0 0 7
Upvotes: 1