0

In MATLAB is there a way to define a variable say runningValue and push values onto it in succession an unknown number of times?

What I have been doing is something like this:

runningValue = 0; for j=1:length(someVector) ... runningValue(end+1) = (some value); ... endfor 

But this forces a leading 0. I know that after all is done I could just put j(1) = []; but I was wondering if there is a more elegant way to do this.

Note that the length of the runningValue variable is not a priori known; in particular, we are not populating length(someVector) elements, referring to the pseudocode above, and the j index is no of use.

2
  • 6
    runningValue = []; maybe for the initialization? Commented Dec 31, 2014 at 15:59
  • Didn't know you could do that - thanks! Commented Dec 31, 2014 at 16:01

2 Answers 2

1

Aside from initializing runningValue to empty, you might as well try reducing the number of appendition, which is an O(n) operation. Instead of appending an element on every loop, you can double the size of the array when it is full. This way, you reduce the number of appendition from n to log(n):

runningValue = []; len = 0; for j = 1:n if (j > len) runningValue = [runningValue zeros(size(runningValue))]; len = length(runningValue); end runningValue(j) = (some value); end runningValue(j+1:len) = []; % If you need to remove the extra zeros 
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply construct a new vector using an existing vector plus another element:

runningValue = []; for j=1:5 runningValue = [runningValue i]; % i can be the element you want to append to the vector end 

This code will output:

runningValue = 1 2 3 4 5 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.