Power series with array input
Mostrar comentarios más antiguos
i is the imaginary unit
i is the imaginary unit
r is a vector of length n: [r(1),...,r(n)]
phi is a 1x300 double, i.e. [phi(1),...,phi(300)]
sum(r(1:n).*(1i.^(1:n))./factorial(1:n))
This would work if there was no phi. But how can I implement the phi here?
sum(r(1:n).*((phi*1i).^(1:n))./factorial(1:n))
Matrix dimensions must agree.
The expected output is the same size as phi. This code would achieve what I want but I want n to be dynamic so the looping is not feasible:
if n==1
R = r(1) * ( i * phi )
elseif n==2
R = r(1) * ( i * phi ) + r(2) * ( i * phi ).^2 / 2;
elseif n==3
R = r(1) * ( i * phi ) + r(2) * ( i * phi ).^2 / 2 + r(3) * ( i * phi ).^3 / 6;
1 comentario
Walter Roberson
el 2 de Mzo. de 2022
"r is a vector of length n: [r(1),...,r(n)]"
Make it a column vector instead of a row vector.
Respuestas (2)
William Rose
el 2 de Mzo. de 2022
Editada: William Rose
el 2 de Mzo. de 2022
[edit: delete a line of unnecessary code]
I assume that, since you have 300 values of phi, that you want to evaluate this sum 300 times - once for each value of phi.
I would make an array with 300 columns and n rows. Then I would add up the elements in each column.
n=20; m=300;
r=rand(n,1); phi=rand(1,m);
a=zeros(n,m);
for i=1:n
a(i,:)=r(i)*(1i*phi).^i/factorial(i);
end
b=sum(a);
fprintf('Size(a)=%d by %d. Size(b)=%d by %d.\n',size(a),size(b));
Try.
1 comentario
William Rose
el 2 de Mzo. de 2022
Inspection of the array a generated by the code above shows that the odd rows are purely imaginary and the even rows are purely real. This makes sense for the equation you provided, since i raised to an odd power is imaginary, and i raised to an even power is real.
My code would have been better if I had used k instead of i as the loop index. Using i as the loop index invites confusion between the index variable and 1i=sqrt(-1). But Matlab is smart, and it did what I intended.
I am not certain what the desired final result is, or what the function does.
If ‘n’ and ‘r’ are row vectors (and by definition the same size), this works —
n = 1:10;
r = randn(size(n));
phi = randn(1,300);
f = sum(r(1:n).*((phi(:)*1i).^(1:n))./factorial(1:n), 2)
Convert ‘phi’ to be a column vector, and then take the sum across the columns, providing an initial column vector as the output as a funciton of ‘phi’. This uses vector-matrix multiploication to produce the vectorised result. Then use sum on that result, or a column sum on the original vector without first taking the row sum, if only a scalar final result is desired.
.
Categorías
Más información sobre MATLAB en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!