Possible Duplicates:
Matlab - building an array while looping Matrix of unknown length in MATLAB?
How do you put all of the "a" values together to form a vector?
for i=1:3
a=2+i
end
Also this is maybe a sty开发者_如何学编程le question but when do you put a semicolon after the end in a for loop such as the one above, also is it proper to put a semicolon after the first line?
You need to index into a
, like this:
for ii=1:3
a(ii) = 2+ii;
end
I prefer to use ii
as a loop variable to avoid clashing with MATLAB's built-in i
. You should also pre-allocate a
if you know the size before the start of the loop, like so:
N = 100;
a = zeros(1,N);
for ii=1:N
a(ii) = 2 + ii;
end
Personally, I never put any punctuation after the for ii=1:3
part, except when writing a one-liner FOR
loop, like so:
for ii=1:N, a(ii) = 2 + ii; end
Note that you can construct this more efficiently as such:
a=1:3;
a=a+2;
The first line assigns a
to be the vector (1,2,3)
, the 2nd line adds 2
to every element.
"Efficiency" doesn't matter much in such a small vector, but in general you'll get much better mileage out of matlab if you get used to thinking more like this.
精彩评论