Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

matlab - Building an array while looping

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...