Hey, I am trying to extract some environmental parameter measurements from netcdf format file and importing them to an excel file. Here is my code:
fullname={'india-20140101-ssrd-run00.nc'};
Varname='var169';
vardata=ncread(fullname,Varname);
i=1;
while i<26
sheet=i;
filename='india-20140101-ssrd-run00.xlsx';
xlRange='B4:IH244';
xlswrite(
filename,vardata(:,:,i),sheet,xlRange);
i=i+1;
end;
I have to read data from several files with names:
india-20140102-ssrd-run00.nc india-20140103-ssrd-run00.nc india-20140104-ssrd-run00.nc india-20140105-ssrd-run00.nc . . .
Is it possible to employ a loop here?

 採用された回答

Chad Greene
Chad Greene 2015 年 3 月 31 日

0 投票

There are a couple of ways you can do this. One way is to populate a list of names manually before starting the loop:
filenames = {'my file 1'; 'my other file'; 'somebody else''s file'};
for k = 1:length(filenames)
disp(filenames{k})
end
Or if you're only incrementing numbers you can do it like this:
for k = 10:13
fullname = ['myfilenumber_',num2str(k),'.nc'];
disp(fullname)
end

4 件のコメント

sujit
sujit 2015 年 3 月 31 日
Thank you Chad..
Stephen23
Stephen23 2015 年 3 月 31 日
編集済み: Stephen23 2015 年 3 月 31 日
Using sprintf is quite a bit faster than concatenating strings:
N = 1e5;
tic
for k = 1:N
['myfilenumber_',num2str(k),'.nc'];
end
toc
tic
for k = 1:N
sprintf('myfilenumber_%i.nc',k);
end
toc
Elapsed time is 5.014318 seconds.
Elapsed time is 0.923741 seconds.
It is a good habit to learn to use sprintf rather than string concatenation!
Chad Greene
Chad Greene 2015 年 3 月 31 日
That's awesome, Stephen!
sujit
sujit 2015 年 4 月 19 日
Thank you Stephen..

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

その他の回答 (1 件)

Brendan Hamm
Brendan Hamm 2015 年 3 月 31 日

1 投票

Sure there are multiple ways to do this.
1. Assuming all of the files are in the same directory (I assume the working) we can use the command:
fileList = dir('india-*'); % Returns a struct with info on the files that begin with 'india-'
fileNames = {fileList.name}; % Extract the file names into a cell array;
for k = 1:length(fileNames)
xlsread(fileNames{k},...); % Fill in the rest here
% Perform more operations here
end
2. You could just start the loop at 20140101 and use strcat. I would use the first method, so will not elaborate here.

質問済み:

2015 年 3 月 31 日

コメント済み:

2015 年 4 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by