简体   繁体   English

在循环内更改数组大小导致Matlab错误

[英]Changing Array size inside a loop causing Error in matlab

I am trying to dynamically set the size of array and store some value in it but it is causing an error. 我正在尝试动态设置数组的大小并在其中存储一些值,但这会导致错误。

here is the code, 这是代码,

syms k
x=[1 0 0 1];
y=[];
for b=1:4
    step1= x(b)*exp(-2*pi*1i*k*((b-1)/length(x)));
    y(b)=step1
end

what i am trying to do is to store each value of step1 in the array 'y'. 我想做的是将step1的每个值存储在数组“ y”中。

and here is the error, 这是错误,

The following error occurred converting from sym to double:
Error using mupadmex
Error in MuPAD command: DOUBLE cannot convert the input expression into a double
array.
If the input expression contains a symbolic variable, use the VPA function instead.
Error in Untitled3 (line 6)
    y(K)=1/exp((pi*k*3*1i)/2)

Depending on what you're trying to do, Matlab struggles to go from double to symbolic, so you should make it clear from the get-go that y is to contain symbolic elements: 根据您要执行的操作,Matlab难以从双精度符号转换为符号精度,因此您应该从一开始就明确指出y包含符号元素:

syms k y
x=[1 0 0 1];
for K=1:4
    step1= x(K)*exp(-2*pi*1i*k*((K-1)/length(x)));
    y(K)=step1
end

Is there a reason why you are using a symbolic variable k and a loop counter K ? 为什么使用符号变量k和循环计数器K是有原因的? It looks like you are confusing the two. 您似乎混淆了两者。 I think this is what you are trying to implement: 我认为这是您要实现的目标:

x=[1 0 0 1];
y=[];

for k=1:4
    y(k)= x(k)*exp(-2i*pi*k*((k-1)/length(x)));    
end

Note: When working with large loops, it is much faster for MATLAB to pre-allocate the array rather than dynamically resizing it. 注意:使用大型循环时,MATLAB预先分配数组而不是动态调整其大小要快得多。 For example by changing y=[]; 例如,通过更改y=[]; to y=zeros(1,4); y=zeros(1,4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM