문제

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.

도움이 되었습니까?

해결책

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top