Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: how to implement a dynamic vector

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.

like image 280
Peterstone Avatar asked Dec 29 '22 03:12

Peterstone


2 Answers

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
like image 127
Charles L. Avatar answered Jan 08 '23 13:01

Charles L.


The trivial solution is:

% if input(i) meets your conditions
output = [output; input(i)]

Though I don't know if this has good performance or not

like image 35
Nathan Fellman Avatar answered Jan 08 '23 15:01

Nathan Fellman