循环内循环索引变量的变化 [英] Change for loop index variable inside the loop

查看:196
本文介绍了循环内循环索引变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在迭代中更改我的循环变量,因为我必须访问循环中的数组元素,它正在改变循环中的w.r.t大小。



这是我的代码片段:

  que = []; 
que = [2,3,4];
全局len;
len = size(que,2)
x = 4;
for i = 1:len
如果x <= 10
que(x)= 5;
len = size(que,2)
x = x + 1;

end
end
que

数组应该打印如下:

  2 3 4 5 5 5 5 5 5 5 
pre>

但是打印如下:

  2 3 4 5 5 5 

在Visual C ++中,正确计算了数组,并打印了整个10个元素的数组,在运行时增加。



如何在Matlab中完成这个?

解决方案

您应该使用 while循环,而不是 for循环执行此操作:

  que = [2 3 4]; 
x = 4;
而x< = 10
que(x)= 5;
x = x + 1;
end

或者,您可以避免使用循环(以下列方式之一对您的代码进行向量化: p>

  que = [2 3 4]; %#你的初始向量
%#选项#1:
que = [que 5. * ones(1,7)]; %#在Que
%#选项#2:
que(4:10)= 5的末尾附加七个fives; %#使用索引扩展que


I need to change my loop variable inside the iteration as I have to access array elements in the loop which is changing w.r.t size inside the loop.

Here is my code snippet:

que=[];
que=[2,3,4];
global len;
len=size(que,2)
x=4;
for i=1:len 
    if x<=10
    que(x)= 5;
    len=size(que,2)
    x=x+1;

    end
end
que

Array should print like:

2 3 4 5 5 5 5 5 5 5 

But it is printed like this:

2 3 4 5 5 5

In Visual C++ the array is calculated correctly and whole array of 10 elements is printed, which increases at run time.

How can I accomplish this in Matlab?

解决方案

You should use a while loop instead of a for loop to do this:

que = [2 3 4];
x = 4;
while x <= 10
  que(x) = 5;
  x = x+1;
end

Or, you can avoid using loops altogether by vectorizing your code in one of the following ways:

que = [2 3 4];             %# Your initial vector
%# Option #1:
que = [que 5.*ones(1,7)];  %# Append seven fives to the end of que
%# Option #2:
que(4:10) = 5;             %# Expand que using indexing

这篇关于循环内循环索引变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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