How to define a vector that its elements are created in a For Loop?

I would like to define a vector,X, with five elements:
syms a
X = zeros(1,5);
X(1) = 1;
for k = 1:4
X(k+1)=X(k)+a^2;
end
Actually I need to have the vector X, that its elements should be based on variable a. But I face an error in MATLAB:
The following error occurred converting from sym to double:
Error using symengine (line 58)
DOUBLE cannot convert the input expression into a double array.
If the input expression contains a symbolic variable, use VPA.
Error in Code2 (line 5)
X(k+1)=X(k)*a^2;
when I write the code above. How to do this? Please Answer me if possible.

3 件のコメント

Adam
Adam 2017 年 1 月 9 日
If you get an error then post it! It's no help to use if you just say you get 'an error' and leave us to try to work out what the error is just by looking at the code.
Stephen23
Stephen23 2017 年 1 月 9 日
@Ali Remo: please edit your question and provide us with the complete error message. This means all of the red text.
John Chilleri
John Chilleri 2017 年 1 月 12 日
You're trying to add a number and a symbol. What is a? are you trying to have the elements of X be strings like x(2) = 'a^2 + 1'?

サインインしてコメントする。

 採用された回答

Steven Lord
Steven Lord 2017 年 1 月 12 日

0 投票

Define X as a sym vector from the start.
X = sym(zeros(1, 5));
Adding a double and a sym results in a sym, but attempting to assign a sym into an element of a double array requires MATLAB to convert the sym into a double. In this case MATLAB cannot perform that conversion, so you receive an error. If instead you attempt to assign a sym into an element of a sym array, no conversion is needed.

その他の回答 (0 件)

カテゴリ

質問済み:

2017 年 1 月 9 日

回答済み:

2017 年 1 月 12 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by