Assigning a value to a new iterate and keeping track of iterate numbers.

1 view (last 30 days)
Here is what I want to get:
x2 = a1
solution is x* = x2
x*=[3 4].
Here is the code that I have:
x1=[1 2];
a1=[3 4];
a2=[7 9];
a3=[6 4];
for k = 1 : 2
if (k+1==3)
disp(sprintf('solution is x*=x%d',k))
else
disp(sprintf('x%d',k+1))= eval(sprintf('a%d',k))
end
end
x*
I am getting an error. I am not sure how to assign a value to a new iterate of x. Basically, I am trying to create x2.

Answers (2)

Matt Fig
Matt Fig on 26 Sep 2012
Don't program this way! Your code will be easy to break, hard to debug and slow. Use Cell arrays or structures instead.
  4 Comments
Image Analyst
Image Analyst on 26 Sep 2012
Edited: Image Analyst on 26 Sep 2012
Did you read the FAQ? Why do you want them to be separate variable names? Why not use a cell array? They're made for that sort of thing - collections of variable-sized things (which actually don't even need to be of the same variable type either).
And I don't even know what an "iterate index number" is. Iterate is a verb that means to repeat something or basically to loop - it is not an adjective. We'll refer to the terms "loop index", "loop counter", or "iteration index", which in your code would be "k", not some new variable with a changing name. So I truly don't know if you're referring to k or x1, x2, and x3.
Matt Fig
Matt Fig on 26 Sep 2012
Use cell arrays!
X{1} = magic(3);
X{2} = 3;
X{3} = [3 5 2];
Now look at X, using cell indexing
X{2}
X{3}

Sign in to comment.


Image Analyst
Image Analyst on 26 Sep 2012
I have almost no idea of what you are asking, despite reading it several times. I do know however that disp() and eval() are totally unnecessary. Plus your second disp() where you're trying to set the result of disp equal to the result of your eval is just going to produce a character by character comparison of those two strings - probably not what you were expecting. Also what does * mean to you? The complex conjugate?
  2 Comments
Del
Del on 26 Sep 2012
Edited: Del on 26 Sep 2012
This is just a small example for a much larger code.
I am trying to figure out how to keep track of the iterate index numbers when using a for loop and if/else statement.
So for this example, I have a starting value for x1.
I am expecting that when k=1, the code will skip the if part and go straight to the else, and assign the value of a_k to x_k+1.
i.e. I want x2 = a1. (i.e. I want x2 to have the value [3 4]).
Next, when k=2, I want the code to terminate (because k+1 =3) and state that the optimal solution (which I am denoting by x*) is x_k, in this case, x_2.

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!