Assigning a value to a new iterate and keeping track of iterate numbers.
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(2 个)
Matt Fig
2012-9-26
Don't program this way! Your code will be easy to break, hard to debug and slow. Use Cell arrays or structures instead.
4 个评论
Image Analyst
2012-9-26
编辑:Image Analyst
2012-9-26
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
2012-9-26
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}
Image Analyst
2012-9-26
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!