vector uses info from itself to grow without for cycle

I need to solve this problem without a for loop:
B= (1:20)
A = [];
A(1) = 1/(1+B(1));
for k = 2:length(B)
A(k,1) = (1-B(k)*sum(A))/(1+B(k));
end
i.e. I need to know if it is possible to get information from prebvious calculation to create a vector, but without a for loop. Thanks.

13 Comments

thank you I modified
in particular this is a case where I need to use previous data to "build" my vector: is there a way to do it without for loop?
What is the final A that your code should be producing?
Let's say it is a vector which needs the sum of the previous values of itself to be computed up to a certain length set by vector B
Rather than making us guess what you mean, I'll repeat, what is the desired final (20x1) A for your code above? At least give us the first few elements of the sequence. Alternatively, please write the recursion mathematically.
B = (1:20)
A = [];
A(1) = 1/(1+S(1));
for k = 2:length(S)
A(k,1) = (1-B(k)*sum(A))/(1+B(k));
end
vector A should be
0.500000000000000
0
-0.125000000000000
-0.100000000000000
-0.0625000000000000
-0.0392857142857143
-0.0265625000000000
-0.0192460317460318
-0.0146651785714286
-0.0115823412698413
-0.00939504794973545
-0.00778140262515264
-0.00655451329837490
-0.00559878557013975
-0.00483920439085755
-0.00422520498138715
-0.00372162668292910
-0.00330337238480719
-0.00295212243142038
-0.00265424172588574
Your code talks about length(S) but it only uses S(1) and no other S element?
I am sorry. New right code:
B= (1:20)
A = [];
A(1) = 1/(1+B(1));
for k = 2:length(B)
A(k,1) = (1-B(k)*sum(A))/(1+B(k));
end
thanks
Are you looking for a closed form formula that can give A(K) without calculating A(K-1) ?
Are you looking for a recusive function that can calculate A(K) by calling itself, without an explicit loop?
yes that is exactly what I want to know if is possible to do somehow
Which of the two?
Recursive functions with no explicit loop are easy for this.
A closed form formula might be difficult.
even recursive function would be nice thank you. I just need an example.

Sign in to comment.

 Accepted Answer

function A = calculate_A(n)
if n == 1
A = 1/2;
else
A_before = calculate_A(n-1);
A = [A_before; (1-n*sum(A_before))/(1+n)];
end
end
Note: this will fail at roughly 75000, due to the recursion using up memory.

More Answers (1)

For the original code in your question. Following is the simplified form.
k = 1:20;
A = 6.^(k-1);

1 Comment

you are right, but I am actually looking for above problem solution, sorry.

Sign in to comment.

Categories

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

Community Treasure Hunt

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

Start Hunting!