gpt4 book ai didi

matlab - 在循环内更改 for 循环索引变量

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:29 24 4
gpt4 key购买 nike

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

这是我的代码片段:

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 个元素的整个数组,该数组在运行时增加。

我如何在 Matlab 中完成此操作?

最佳答案

你应该使用 while loop而不是 for loop这样做:

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

或者,您可以通过 vectorizing your code 完全避免使用循环通过以下方式之一:

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

关于matlab - 在循环内更改 for 循环索引变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2832020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com