using a variable to call another variable

Hello all,
After doing analysis in some other software I get text files namely Eigen_1.txt, Eigen_2.txt.......Eigen_k.txt and each file is 4x4 matrix. I want to read each file, get the (1,3) value and assign it to variable T1_1, T1_2.......T1,k and then use this value to get omega1_1 and so on. I have used eval command which works fine, but is there any other way to solve this without using eval command.
for n = 1:k
temp = readmatrix(strcat('.\Results\Eigen_',num2str(n),'.txt'),'delimiter',' ');
eval(['T1_',num2str(n),'=temp(1,3)']);
eval(['omega1_',num2str(n),' = 6.2832/T1_',num2str(n),]);
end

4 件のコメント

Stephen23
Stephen23 2022 年 9 月 16 日
"I have used eval command which works ..."
not very well: dynamically accessing variable names like that requires writing code which is slow, inefficient, insecure, obfuscated, buggy and hard to debug:
"...but is there any other way to solve this without using eval command."
The name MATLAB comes from MATrix LABoratory, so the simple and obvious solution is to use matrices, just like MATLAB is designed for. This is exactly what the introductory tutorials show too:
Irshad Qureshi
Irshad Qureshi 2022 年 9 月 16 日
I agree with you and will go through tutorials. I am a novice in MATLAB so still learning.
Thanks,
Irshad Qureshi
Irshad Qureshi 2022 年 9 月 16 日
thanks, Stephen.

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

 採用された回答

Chunru
Chunru 2022 年 9 月 16 日
編集済み: Chunru 2022 年 9 月 16 日

0 投票

T1 = zeros(k, 1); % use array instead of T1_, T1_2, ...
omega1 = zeros(k, 1);
for n = 1:k
temp = readmatrix(strcat('.\Results\Eigen_',num2str(n),'.txt'),'delimiter',' ');
% eval(['T1_',num2str(n),'=temp(1,3)']);
% eval(['omega1_',num2str(n),' = 6.2832/T1_',num2str(n),]);
T1(n) = temp(1, 3);
omega1(n) = 2*pi/T1(n);
end

1 件のコメント

Irshad Qureshi
Irshad Qureshi 2022 年 9 月 16 日
Thanks. Its working and its much easier also.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by