フィルターのクリア

character to variable that already exists in the workspace

2 ビュー (過去 30 日間)
Ziv Kassner
Ziv Kassner 2015 年 2 月 25 日
編集済み: Stephen23 2023 年 9 月 12 日
I want to make a "for loop" that uses some variables that looks like this: score1, score2, score3,...score21. My problem is that I cannot connect both string 'score' and the number (represented by 'i') as a whole string. the script is:
for i=1:21
[r c]=size(strcat('score', num2str(i)));
for j=2:r
strcat('cscore', num2str(i))(j-1)=strcat('score', num2str(i))(j)+strcat('score', num2str(i))(j-1);
end
end
after this, the value of this variable is a 'char' rather that a string.
thank you, Ziv.

採用された回答

Geoff Hayes
Geoff Hayes 2015 年 2 月 25 日
編集済み: Geoff Hayes 2015 年 2 月 25 日
Ziv - use sprintf to "concatenate" the number to the string. Try
for k=1:21
str = sprintf('score%d',k);
end
str will be one of score1, score2, etc. This code will create the variable name and then you will have to evaluate it using (most likely) eval.
But ask yourself is this really necessary? Can't you put all of these scores into a matrix or cell array and so avoid these individual variables? While MATLAB allows you to do the above and evaluate strings etc. it is not usually a good habit to get in to.
  2 件のコメント
Ziv Kassner
Ziv Kassner 2015 年 2 月 25 日
Thank you very much. the problem is that I have many vectors with different lengths, so I can't put them together in the same matrix.
Geoff Hayes
Geoff Hayes 2015 年 2 月 25 日
Ziv - since the vectors are of different lengths, you can use a cell array to store each one.

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2015 年 2 月 25 日
You should store your data into structs or in cell arrays:
scoreStruct(1).values = [1 2 3]
scoreStruct(2).values = 10
scoreStruct(3).values = 10:20
scoreCell = {[1 2 3], 10, 10:20}
Learn about structs and cell arrays now an save yourself a lot a of trouble in the future!
Never ever use eval for this !! (Can I make this red?)

カテゴリ

Help Center および File ExchangeScope Variables and Generate Names についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by