views:

35

answers:

3

I've got a bunch of values that are all assigned the same variable due to running through a for loop several times, so for example:

d = 3.44434 d = 2.4444 d = 2.7777

How do I put them all into a vector?

+2  A: 

If you know the number of values beforehand, you can speed things up (if there are several elements) by preallocating.

Code

num_elements = 10;
vector = zeros(num_elements,1);
for i = 1:num_elements
   vector(i) = SomeFunction();
end

If you don't know the number of elements before running the loop,

Code

vector = [];
some_condition = true;
while some_condition == true
   vector(end+1) = SomeFunction();
   some_condition = SomeConditionFunction();
end
Jacob
+1  A: 

If you need a loop for your operations, use Jacob's answer. Otherwise, if you're doing a relatively simple operation, you may be able to vectorize. For example:

x=1:10; % input vector
rootofx=sqrt(x); % output vector

The ./ .* and .^ operators are useful if you want to perform element-wise operations.

Doresoom
A: 

I made a video about this:

http://blogs.mathworks.com/videos/2007/08/20/matlab-basics-video/

MatlabDoug