4

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!

Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
Mark
  • 315
  • 3
  • 4
  • 6
  • You will probably find the following links of interest: http://stackoverflow.com/questions/1680557/optimizing-extraction-of-data-from-a-matlab-matrix, http://stackoverflow.com/questions/132092/what-are-your-favourite-matlab-octave-programming-tricks, http://stackoverflow.com/questions/1450322/matlab-excluding-data-outside-1-standard-deviation, http://stackoverflow.com/questions/2202641/how-do-i-compare-all-elements-of-two-arrays-in-matlab – mtrw Mar 19 '10 at 22:30
  • 1
    let me add this one to the list: http://stackoverflow.com/questions/1548116/matrix-of-unknown-length-in-matlab – Amro Mar 19 '10 at 22:42

2 Answers2

7

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.

mtrw
  • 34,200
  • 7
  • 63
  • 71
2

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);
Michael Kopinsky
  • 884
  • 1
  • 7
  • 14
  • Just a small precission. The mask must be an array of logicals, it seems. I tested with select=[0 1 0 1...] and got an error "Subscript indices must either be real positive integers or logicals". Then I tried with select=[false true false true...] and it worked as expected. – Miguel Muñoz Aug 18 '16 at 15:13