-2

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 style 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?

Community
  • 1
  • 1
Go Spain
  • 1
  • 1
  • 1
  • I guess this only a simplified example and you actually more in your for-loop. If not, you can vectorize everything to a one-liner: `a = 2 + (1:3);` – groovingandi Jul 07 '10 at 09:59
  • Duplicate: http://stackoverflow.com/questions/2480933/matlab-building-an-array-while-looping, http://stackoverflow.com/questions/1548116/matrix-of-unknown-length-in-matlab – gnovice Jul 07 '10 at 13:37

2 Answers2

0

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
Edric
  • 23,676
  • 2
  • 38
  • 40
0

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.

Donnie
  • 45,732
  • 10
  • 64
  • 86