开发者

Building an array while looping

开发者 https://www.devze.com 2022-12-24 01:44 出处:网络
I have a for loop that loops over one array... for i=1:length(myArray) In this loop, I want to do check on the value of myArray and add it to another array myArray2 if it meets certain conditions.

I have a for loop that loops over one array...

for i=1:length(myArray)

In this loop, I want to do check on the value of myArray and add it to another array myArray2 if it meets certain conditions. I looked through the MATLAB docs, but couldn't find anything on creating arrays without declaring all their values on initialization or reading data into them in one shot开发者_运维百科.

Many thanks!


I'm guessing you want something more complicated than

myArray = [1 2 3 4 5];
myArray2 = myArray(myArray > 3);

The easiest (but slowest) way to do what you're asking is something like

myArray2 = [];
for x = myArray
    if CheckCondition(x) == 1
        myArray2 = [myArray2 x]; %# grows myArray2, which is slow
    end;
end;

You can sort of optimize this with something like

myArray2 = NaN(size(myArray));
ctr = 0;
for x = myArray
    if CheckCondition(x) == 1
        ctr = ctr + 1;
        myArray2(ctr) = xx;
    end;
end;
myArray2 = myArray2(1:ctr); %# drop the NaNs

You might also want to look into ARRAYFUN.


For the most part, the way to do what you're describing is like mtrw said in the first example.

Let's say data = [1 2 3 4 5 6 7 8 9 10], and you want to get only the even numbers.

select = mod(data,2)==0; % This will give a binary mask as [0 1 0 1 0 1 0 1 0 1].

If you do data2=data(select), it will give you [2 4 6 8 10].

Of course, the shorter way to do this is as mrtw had in example 1:

data2=data(some_criteria);
0

精彩评论

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

关注公众号