0

I wrote a code in Matlab which I predefine the variable "a" and then set up a for loop of 5 iterations where the variable "a" goes through some basic operations. However, the for loop output only saves the fifth iteration of "a." How do I save all 5 iterations in a 1x5 array?

The code is as follows:

a = 10;
k = 0.5;
n = 2;
for m = 1:5
    a = a + (a*k) + n;
end

Edit: I just found it that I have to create a new variable.

a = 10;
k = 0.5;
n = 2;
a_n = zeros(1,5);

for m = 1:5
    a = a + (a*k) + n;
    a_n(m) = a;
end
3
  • 4
    .. What language is that? Without knowing, I don't know what the syntax is to create an array. (Of course you could use Google with "[language] array".) Commented Oct 17, 2013 at 18:27
  • Sorry, I forgot to mention the language is in Matlab. Commented Oct 17, 2013 at 18:34
  • Declaration of new variable a_n = zeros(1,5); is redundant in Matlab Commented Oct 17, 2013 at 18:52

2 Answers 2

2

You may need to store value of a after each iteration into an another variable x

a = 10;
k = 0.5;
n = 2;
for m = 1:5
    a = a + (a*k) + n;
    x(m) = a;
end
x

Output:

x =
    17.000    27.500    43.250    66.875   102.312
Sign up to request clarification or add additional context in comments.

1 Comment

The array syntax is correct on this answer. This should be the chosen answer.
1

You would need to use a different variable to store the 5 iterations as an array.

Code would look something like this:

a = 10;
k = 0.5;
n = 2;
b = [];
for m = 1:5
   a = (a + (a*k) + n)
   b = [b a];
end

You can now print b for all 5 iteration values.

Here is an alternate way to update values into the 1-D matrix.

5 Comments

How do you know what language this is?
Based on the syntax of for loop I guessed Matlab, but I could be wrong here.
Terry, please choose the other answer as the chosen answer, it has the proper array syntax. I'll update my answer with that change as well.
@PraveenramBalachandar apart from the syntax, your code won't give desired output. it's not storing previously processed value of a for next iteration
You're right, I overlooked that as well. Thanks, I'll fix it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.