Building an array during looping

I have a for loop that iterates over a single array ...

for i=1:length(myArray) 

In this loop, I want to check the value of myArray and add it to another myArray2 array if it meets certain conditions. I looked through MATLAB documents, but could not find anything when creating arrays without declaring all their values ​​when initializing or reading data in them with one shot.

Many thanks!

+4
source share
2 answers

I guess you need something more complex than

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

The easiest (but slowest) way to do what you ask is something like

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

You can optimize this with

 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 can also watch ARRAYFUN .

+7
source

For the most part, the way to do what you are describing is similar to mtrw mentioned in the first example.

Say data = [1 2 3 4 5 6 7 8 9 10] and you want to get only 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, a shorter way to do this, since mrtw had in example 1:

 data2=data(some_criteria); 
+2
source

Source: https://habr.com/ru/post/1304621/


All Articles