Creating variables in a foor loop using num2str

19 ビュー (過去 30 日間)
Mady
Mady 2022 年 11 月 23 日
編集済み: Stephen23 2022 年 12 月 8 日
Hi,
title probably says it all. I want to create variables according to the i in the loop. I just don't even know if I can incorporate the function (I've already tried num2str, eval, evalc, sprintf) into variable definition. Below is a non-working code just to illustrate what I mean to do (hopefully). This example is just for 3 different variables but later on, I need to do this for about 60 more variables. I just cannot quite put my hand on the right formulation of the loop.
Thank you for any advices
%%% years_10 = [xvalues, yvalues]... n*2 matrices
years_10=readmatrix('10_years.csv');
years_20=readmatrix('20_years.csv');
years_30=readmatrix('30_years.csv');
for i=10:10:30
years_num2str(i) = readmatrix(sprintf('%d_years.csv',i);
end
  2 件のコメント
Walter Roberson
Walter Roberson 2022 年 11 月 23 日
Why do you think this is necessary? Why not use a cell array instead?
Stephen23
Stephen23 2022 年 12 月 8 日
編集済み: Stephen23 2022 年 12 月 8 日
The easy, simple, and very efficient approach is to use indexing into one array, e.g. a cell array or structure array.
Using indexing is shown in the MATLAB documentation:

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

採用された回答

William Rose
William Rose 2022 年 11 月 23 日
編集済み: William Rose 2022 年 11 月 23 日
[edit: change "v" to "s" in my description, to match the code]
N=50;
for i=10:10:N, s.(strcat('a',num2str(i)))=i^2; end
disp(s)
a10: 100 a20: 400 a30: 900 a40: 1600 a50: 2500
creates a structure s with fields a10, a20, ..., a50. Each one equals a scalar. You could initialize each one to be a vector or array, if you prefer.
  5 件のコメント
Mady
Mady 2022 年 12 月 7 日
Thank you @William Rose for quite a handy solution. The tutorial about Dynamic variable naming is very useful, lots of new informations :)
William Rose
William Rose 2022 年 12 月 8 日
@Jiri Kovar, you're welcome.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by