Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building an array while looping

Tags:

arrays

matlab

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!

like image 248
Mark Avatar asked Jan 23 '23 10:01

Mark


2 Answers

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.

like image 191
mtrw Avatar answered Jan 30 '23 08:01

mtrw


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);
like image 40
Michael Kopinsky Avatar answered Jan 30 '23 09:01

Michael Kopinsky