Matlab: how to implement a dynamic vector

I mean an example like this. I have a function to parse 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 when begging I don’t know how many elements need to be stored in the “output”, I don’t know its size. I have a loop, inside I go around the vector, "enter" through the index. When I consider that some element of this vector captures the values ​​of "input" and it is stored in the vector "output" through the following sentence:

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 message if I did not announce the output before. I don’t want to “declare” the “output” before reaching the loop as output = input, because it saves the values ​​from the input, in which I am not interested, and I should think about how to delete all the values ​​that I saved are relevant to me. Does anyone cover me in this matter? Thanks.

+4
source share
3 answers

How complicated is the logic in the for loop?

If it is simple, something like this will work:

 output = input ( logic==true ) 

Alternatively, if the logic is complex and you are dealing with large vectors, I would first select a vector that stores whether to save the element or not. Here is a sample 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 
+7
source

Trivial solution:

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

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

+2
source

If N not too large to cause memory problems, you can preassign output to a vector of the same size as input , and remove all unnecessary elements at the end of the loop.

 output = NaN(N,1); for i=1:N ... output(i) = input(i); ... end output(isnan(output)) = []; 

There are two alternatives.

If output is too large, if it was assigned size N , or if you did not know the upper limit of output size, you can do the following

 lengthOutput = 100; output = NaN(lengthOutput,1); counter = 1; for i=1:N ... output(counter) = input(i); counter = counter + 1; if counter > lengthOutput %# append output if necessary by doubling its size output = [output;NaN(lengthOutput,1)]; lengthOutput = length(output); end end %# remove unused entries output(counter:end) = []; 

Finally, if N is small, it is quite normal to call

 output = []; for i=1:N ... output = [output;input(i)]; ... end 

Note that performance deteriorates dramatically if N gets large (say> 1000).

+1
source

Source: https://habr.com/ru/post/1333794/


All Articles