Assigning a value to a new iterate and keeping track of iterate numbers.
이전 댓글 표시
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.
답변 (2개)
Matt Fig
2012년 9월 26일
0 개 추천
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일
See the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F for reasons why.
Del
2012년 9월 26일
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일
0 개 추천
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
Image Analyst
2012년 9월 26일
You can use "break" to exit out of a for loop.
카테고리
도움말 센터 및 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!