0

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 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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: 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: True, but the question concerns extracting certain elements, and thus I assume the final size is not known beforehand.
@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.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.