sha*_*ana 5 indexing matlab loops for-loop dynamic
我需要在迭代中更改我的循环变量,因为我必须访问循环中的数组元素,这会改变循环内部的wrt大小.
这是我的代码片段:
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
Run Code Online (Sandbox Code Playgroud)
数组应该打印如下:
2 3 4 5 5 5 5 5 5 5
Run Code Online (Sandbox Code Playgroud)
但它打印如下:
2 3 4 5 5 5
Run Code Online (Sandbox Code Playgroud)
在Visual C++中,正确计算数组,并打印10个元素的整个数组,这在运行时会增加.
我怎样才能在Matlab中实现这一目标?
gno*_*ice 10
que = [2 3 4];
x = 4;
while x <= 10
que(x) = 5;
x = x+1;
end
Run Code Online (Sandbox Code Playgroud)
或者,您可以通过以下方式之一矢量化代码来完全避免使用循环:
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
Run Code Online (Sandbox Code Playgroud)