What is the final value of this variable when executed in MATLAB?

Okay so I am supposed to find a final value given the code below. I know how to do it on MATLAB but I don't understand how to do it without MATLAB and apparently I'm supposed to know how to get the final_value without using MATLAB. Code:
i = 3;
j = 2;
k = 4;
final_value = 2;
for i = 1:5
final_value = final_value + 2*i+3*j+k;
end
When I do it in MATLAB i get an answer of 82 (which I'm not sure if it is right), but whether it's right or wrong, how would I get the answer without using matlab?

 Accepted Answer

Just take each term that gets added to final_value in the for-loop and add up what happens for each iteration. E.g., the term that gets added each time is 2*i+3*j+k so just write that down for each value of the for-loop index i:
For i=1, the term is:
2*1+3*2+4
For i=2, the term is:
2*2+3*2+4
Etc. So just do this for each value of i and then add them all up. Since final_value starts with a value of 2, the final answer will be:
2 + (2*1+3*2+4) + etc.
You can do the rest.

5 Comments

I did this and got 14, 16, 18, 20, 22, which gave me an answer of 90.
But when I executed the command on matlab it gave me 82...
The terms go from 12 to 20, not 14 to 22. E.g.,
2*1 + 3*2 + 4 = 2 + 6 + 4 = 12
Oh it does make sense that way, but how come it starts at 12? Don't we also have to add final_value which is 2?
My sequence was only for the additional terms that get added to final_value. The initial 2 of final_value only gets into the final answer once, not five times.
I see, thank you very much.

Sign in to comment.

More Answers (0)

Categories

Asked:

Bob
on 19 Oct 2016

Commented:

Bob
on 19 Oct 2016

Community Treasure Hunt

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

Start Hunting!