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

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

问题描述

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

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.

这是我的代码片段:

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

数组应该打印如下:

2 3 4 5 5 5 5 5 5 5 

但它是这样打印的:

2 3 4 5 5 5

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

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

如何在 Matlab 中完成此操作?

How can I accomplish this in Matlab?

推荐答案

您应该使用 while 循环 而不是 for 循环来做到这一点:

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

或者,您可以通过 以下列方式之一对您的代码进行矢量化:

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天全站免登陆