Reputation: 1
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?
Upvotes: 0
Views: 95
Reputation: 7458
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.
Upvotes: 1
Reputation: 34621
If you know the number of values beforehand, you can speed things up (if there are several elements) by preallocating.
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,
vector = [];
some_condition = true;
while some_condition == true
vector(end+1) = SomeFunction();
some_condition = SomeConditionFunction();
end
Upvotes: 2