Clear Filters
Clear Filters

Use num2str in for loop

5 views (last 30 days)
Mac
Mac on 29 Oct 2023
Commented: Mac on 29 Oct 2023
Good day. I know is simple but I can't find the solution to this. I want to call some data (M3 to M11) in for loop using num2str, but it does not work. Below is the code, specifically in bold.
M3 = mean(Mar, 3);
M4 = mean(Apr, 3);
M5 = mean(May, 3);
M6 = mean(Jun, 3);
M7 = mean(Jul, 3);
M8 = mean(Aug, 3);
M9 = mean(Sep, 3);
M10 = mean(Oct, 3);
M11 = mean(Nov, 3);
[xx,yy]=meshgrid(lon,lat);
b=-18:2:18;
f = figure;
t = tiledlayout(f, 3, 3);
for i = 3:11
nexttile(t)
m_proj('miller','lon',[110 130],'lat',[0 15]);
m_contourf(xx,yy,['M', num2str(i)], b,'linestyle','none');
colormap(m_colmap('BOD',256))
................
  12 Comments
Mac
Mac on 29 Oct 2023
Thanks @Stephen23. Appreciate it.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 29 Oct 2023
Please read http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval for information about why we strongly recommend against creating variable names dynamically.
M3 = mean(Mar, 3);
M4 = mean(Apr, 3);
M5 = mean(May, 3);
M6 = mean(Jun, 3);
M7 = mean(Jul, 3);
M8 = mean(Aug, 3);
M9 = mean(Sep, 3);
M10 = mean(Oct, 3);
M11 = mean(Nov, 3);
M = {[], [], M3, M4, M5, M6, M7, M8, M9, M10, M11}; %two dummy so M{i} corresponds to M_i
for i = 3:11
nexttile(t)
m_proj('miller','lon',[110 130],'lat',[0 15]);
m_contourf(xx,yy,M{i}, b,'linestyle','none');
colormap(m_colmap('BOD',256))
  1 Comment
Mac
Mac on 29 Oct 2023
Thanks a lot Walter. Noted. Thank to both for the enlightenment.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!