looping through files, filenames varying by number in name gives num2str error

3 次查看(过去 30 天)
Hello everyone, so I wanna do this really simple loop:
for i = 5:9
A = squeeze(nc_varget('/home/forsker1/Documents/GL2/2001-2010/DMI-HIRHAM5_GL2_2001_' num2str(i) '_maskgreenlandglacier.nc','tas'));
%do something
end
but it keeps underlining the num2str(i) and the second last bracket, with the note "invalid syntax, possibly )]} missing". And when I run it I get the error "unexpected Matlab expression". I'm sorry,I know this should be so easy but I just don't get what I'm doing wrong here and it drives me crazy.

采纳的回答

Guillaume
Guillaume 2016-11-22
You need to tell matlab that you're concatenating strings, thus wrap your concatenation in []:
['/home/forsker1/Documents/GL2/2001-2010/DMI-HIRHAM5_GL2_2001_' num2str(i) '_maskgreenlandglacier.nc']
or in my opinion, better yet, use sprintf:
A = squeeze(nc_varget(sprintf('/home/forsker1/Documents/GL2/2001-2010/DMI-HIRHAM5_GL2_2001_%d_maskgreenlandglacier.nc', i),'tas'))

更多回答(1 个)

KSSV
KSSV 2016-11-22
for i = 5:9
A = squeeze(nc_varget(strcat('/home/forsker1/Documents/GL2/2001-2010/DMI-HIRHAM5_GL2_2001_', num2str(i), '_maskgreenlandglacier.nc'),'tas'));
%do something
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by