Matlab: how to implement a dynamic vector

Peterstone picture Peterstone · Dec 30, 2010 · Viewed 10.7k times · Source

I am refering to an example like this I have a function to analize the elements of a vector, 'input'. If these elements have a special property I store their values in a vector, 'output'. The problem is that at the begging I don´t know the number of elements it will need to store in 'output'so I don´t know its size. I have a loop, inside I go around the vector, 'input' through an index. When I consider special some element of this vector capture the values of 'input' and It be stored in a vector 'ouput' through a sentence like this:

For i=1:N %Where N denotes the number of elements of 'input'
...
output(j) = input(i);
...
end

The problem is that I get an Error if I don´t previously "declare" 'output'. I don´t like to "declare" 'output' before reach the loop as output = input, because it store values from input in which I am not interested and I should think some way to remove all values I stored it that don´t are relevant to me. Does anyone illuminate me about this issue? Thank you.

Answer

Charles L. picture Charles L. · Dec 30, 2010

How complicated is the logic in the for loop?

If it's simple, something like this would work:

output = input ( logic==true )

Alternatively, if the logic is complicated and you're dealing with big vectors, I would preallocate a vector that stores whether to save an element or not. Here is some example code:

N = length(input); %Where N denotes the number of elements of 'input'
saveInput = zeros(1,N);  % create a vector of 0s
for i=1:N
    ...
    if (input meets criteria)
        saveInput(i) = 1;
    end
end
output = input( saveInput==1 ); %only save elements worth saving