imbibi
imbibi

Reputation: 1

Forming vectors from the same assigned value

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

Answers (2)

Doresoom
Doresoom

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

Jacob
Jacob

Reputation: 34621

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

Upvotes: 2

Related Questions