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

 Accepted Answer

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 (./).
.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!