建立一个数组,而循环 [英] Building an array while looping

查看:105
本文介绍了建立一个数组,而循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环遍历一个阵列...

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

for i=1:length(myArray)

在这个循环中,我想要做的检查myArray的价值,它是否符合一定的条件添加到另一个阵列myArray2。我通过MATLAB文档看去,却找不到上没有宣布在初始化所有的价值或将数据读入其中一炮打响创建阵列东西。

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.

非常感谢!

推荐答案

我猜你想要的东西复杂得多

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

您可能还需要寻找到 ARRAYFUN

这篇关于建立一个数组,而循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆