a = [1; 2; 3]
a = [1, 2, 3] % avoid
a = zeros(10,1)
a = ones(10,1)
a = NaN(10,1)
a = linspace(0,1,10)
a = logspace(-1,1,10)
% change one element
a(2) = 2;
% change many elements
a(2:4) = [2;3;4];
a(:) = 1;
% note that this is different from
a = 1;
a = linspace(0,1,100);
b = 0*a;
c = NaN*a; % preferred
This is the standard way you would do this
a = linspace(0,1,100)
b = NaN*a;
for i = 1:length(a)
b(i) = a(i)^2;
end
This is bad (because the size of the vector changes every iteration)
a = linspace(0,1,100)
b = [];
for i = 1:length(a)
b(i) = a(i)^2;
end
Looping backwards is OK, and automatically pre-allocates a vector
a = linspace(0,1,100)
b = [];
for i = 1ength(a):-1:1
b(i) = a(i)^2;
end
Note that not all operations can be vectorized; you may have to use for loops
a = linspace(0,1,100);
b = a.^2; % the . is important