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?
3 Answers
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).
Comments
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.
4 Comments
yourList = zeros(whatever,1). Growing an array inside a loop can slow down the loop a lot.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.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);