tags:

views:

71

answers:

3

I run through a for loop, each time extracting certain elements of an array, say element1, element2, etc. How do I then pool all of the elements I've extracted together so that I have a list of them?

+1  A: 

Build the list as you go:

for i = 1:whatever
    ' pick out theValue
    yourList(i) = theValue
end

I'm assuming that you pick out one element per loop iteration. If not, just maintain a counter and use that instead of i.

Also, I'm not assuming you're pulling out your elements from the same position in your array each time through the loop. If you're doing that, then look into Donnie's suggestion.

John at CashCommons
If you're only appending to your array, you can use (end+1) instead of keeping a counter. The result variable should be initialized before, for example to [].
Kleist
+1 for the circular reference :)
walkytalky
@Kleist: It is much preferable to initialize the variable to its final size, e.g. `yourList = zeros(whatever,1)`. Growing an array inside a loop can slow down the loop a lot.
Jonas
@Jonas: True, but the question concerns extracting certain elements, and thus I assume the final size is not known beforehand.
Kleist
@Kleist: In that case, you can preallocate with `NaN(size(sourceArray))` - because that's how many elements you'll pick at most, and remove all the NaNs after the end of the loop.
Jonas
+3  A: 

John covered the basics of for loops, so...

Note that matlab code is often more efficient if you vectorize it instead of using loops (this is less true than it used to be). For example, if in your loop you're just grabbing the first value in every row of a matrix, instead of looping you can do:

yourValues = theMatrix(:,1)

Where the solo : operator indicates "every possible value for this index". If you're just starting out in matlab it is definitely worthwhile to read up on matrix indexing in matlab (among other topics).

Donnie
A: 

In MATLAB, you can always perform a loop operation. But the recommended "MATLAB" way is to avoid looping:

Suppose you want to get the subset of array items

destArray = [];
for k=1:numel(sourceArray)
   if isGoodMatch(sourceArray(k))
      destArray = [destArray, sourceArray(k)]; % This will create a warning about resizing
   end
end

You perform the same task without looping:

matches = arrayfun(@(a) isGoodMatch(a), sourceArray);  % returns a vector of bools
destArray = sourceArray(matches);
Andrew Shepherd

related questions