How do I run an array through a loop and store the results?

I am trying to run a loop element by element and then store the results as elements in a different array.
I can make it work if I use a scalar as the input but I want to run 10 scalars through the loop and store the results as an array.
Really don't know how to do it despite working at it for hours now.
Here is the code as it is now
clc;
clear;
k=1;
x=linspace(0,(pi/2),10);
sum=zeros(1,10);
while k<10 && abs((-1)^(k-1)*(x^(2*(k-1)))/factorial(2*(k-1)))>0.001
s=x(kidx);
sum = sum + (-1)^(k-1)*(x^(2*(k-1)))/factorial(2*(k-1));
k=k+1;
disp(sum)
end
end

 采纳的回答

Subscript ‘x’ in each call to it to use each element as a scalar, then calculate the sum at the end —
k=1;
x=linspace(0,(pi/2),10);
v=zeros(1,10);
while k<10 && abs((-1)^(k-1)*(x(k)^(2*(k-1)))/factorial(2*(k-1)))>0.001
% s=x(kidx);
v(k) = (-1)^(k-1)*(x(k)^(2*(k-1)))/factorial(2*(k-1))
k=k+1;
end
v = 1×10
1 0 0 0 0 0 0 0 0 0
v = 1×10
1.0000 -0.0152 0 0 0 0 0 0 0 0
sumv = cumsum(v);
disp(sumv)
1.0000 0.9848 0.9848 0.9848 0.9848 0.9848 0.9848 0.9848 0.9848 0.9848
Vectorising it would be more efficient —
kv = 1:numel(x);
v = (-1).^(kv-1).*(x.^(2*(kv-1)))./factorial(2*(kv-1))
v = 1×10
1.0000 -0.0152 0.0006 -0.0000 0.0000 -0.0000 0.0000 -0.0000 0.0000 -0.0000
sumv = cumsum(v)
sumv = 1×10
1.0000 0.9848 0.9854 0.9854 0.9854 0.9854 0.9854 0.9854 0.9854 0.9854
Note — The use of element-wise multiplication (.*), exponentiation (.^), and division (./).
.

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by