开发者

For loops in Matlab

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?


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


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.


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜