开发者

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 an开发者_JAVA技巧d 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.


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


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


If N is not too big so that it would cause you memory problems, you can pre-assign output to a vector of the same size as input, and remove all useless 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 would be too big if it was assigned the size of N, or if you didn't know the upper limit of the size of output, 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 perfectly fine to call

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

Note that performance degrades dramatically if N becomes large (say >1000).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜