1

In Matlab I am trying to assign values of a variable generated within a for-loop to an array.

for i=1:4
S = 2*i;
P(i) = S;
end

S is generated within the for loop and all the values it will have are: 2, 4, 6 and 8.

Now I want to assign each of these values of S to an array P such that I want

P(1) = 2, P(2) = 4, P(3) = 6, P(4) = 8

But the for-loop I have included does not work and I have no idea why. First of all it creates a char rather than creating and array. Secondly, none of the values are added and at the end P is empty.

I am not sure why its not working? Does anybody know how to fix this?

1
  • Try to first allocate P by P=zeros(4,1); Commented Mar 4, 2015 at 10:28

1 Answer 1

1

You already have a variable P which is a char. Subscript assigning does not change the type of the variable. Delete it using clear P and you get what you want. Alternatively you can overwrite P with zeros as Photon suggested.

This may also be solved without a loop:

P=2.*[1:4]

or:

P=2:2:8
Sign up to request clarification or add additional context in comments.

Comments

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.