Sufiyan Ghori
Sufiyan Ghori

Reputation: 18743

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'.

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)

Upvotes: 0

Views: 756

Answers (2)

Rasman
Rasman

Reputation: 5359

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:

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

Upvotes: 1

Bruce Hart
Bruce Hart

Reputation: 214

Is there a reason why you are using a symbolic variable k and a loop counter 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. For example by changing y=[]; to y=zeros(1,4);

Upvotes: 0

Related Questions