changing part of the name of a variable inside a "for" loop

1 回表示 (過去 30 日間)
vaggelis vaggelakis
vaggelis vaggelakis 2012 年 10 月 6 日
回答済み: James Cress 2018 年 6 月 12 日
hello everyone!
let's say i have the equation between two variables:
DT10sec= A*T10sec
How can i use a "for" loop to calculate the equation
DT20sec= A*T20sec
DT30sec= A*T30sec,
DT40sec= A*T40sec,... etc
How can i interfere in just a part of the name of a variable?
  3 件のコメント
Matt J
Matt J 2012 年 10 月 6 日
編集済み: Matt J 2012 年 10 月 6 日
How did you generate variables T10sec, T20sec, etc... in the first place? Did you have an automated procedure for that? If so, how is what you're trying to do now significantly different?
I assume you know, by the way, that this is a bad thing to do. You could have just had T(1), T(2), T(3), etc... and then simply done DT=A*T.
vaggelis vaggelakis
vaggelis vaggelakis 2012 年 10 月 6 日
DT and T are matrices. DT10sec is the matrix i want to calculate when T10sec is known. I am asking if it's possible to program a change on the name of the variable, i.e.
for i=10:10:40 DT"i"sec= A* T"i"sec end

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

採用された回答

Matt Fig
Matt Fig 2012 年 10 月 6 日
編集済み: Matt Fig 2012 年 10 月 6 日
Do not program this way! The use of eval is slow, hard to read, difficult to process, works without taking advantage of MATLAB indexing, leads to workspace bloat, locks you into using eval every time you need such variables and prone to bugs. Instead use cell arrays or structures...
It is basic MATLAB not to use eval, in fact it is so common a question that there is a FAQ explaining how to avoid it and alternatives that are standard MATLAB.

その他の回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 6 日
for k=20:10:40
eval(sprintf('DT%dsec=A*%dsec',k,k))
end

Wayne King
Wayne King 2012 年 10 月 6 日
編集済み: Wayne King 2012 年 10 月 6 日
You can use eval() for this. For example to to get y1, y2, y3, such that
y1 = x^1;
y2 = x^2;
x = 2;
for ii = 1:10
eval(['y' num2str(ii) '=x^' num2str(ii) ';']);
end
Now you have variables, y1 through y10 in your workspace. There are good reasons not to do this obviously because you can proliferate the number of variables quite excessively.

James Cress
James Cress 2018 年 6 月 12 日
You could do this very easily with a struct.
data = struct;
for k = 1:4
data.(['DT' num2str(k*10) 'sec'])= A*data.(['T' num2str(k*10) 'sec']);
end

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by