Convert and save multiple .nc file into .asc by keeping the original filename
7 views (last 30 days)
Show older comments
MAT NIZAM UTI
on 17 Sep 2023
Commented: MAT NIZAM UTI
on 17 Sep 2023
Hi, I have created a code to convert the .nc file into .asc file. However, I want to convert all the .nc file one by one and save it one by one into .asc file without changing the orignal filename of .nc. For example
.nc file: SM_OPER_MIR_OSUDP2_20220101T092744_20220101T102058_700_001_1.nc
convert it into
.asc file: SM_OPER_MIR_OSUDP2_20220101T092744_20220101T102058_700_001_1.asc
However, I am stuck at converting it one by one and save it into .asc file.
Here is my coding
clear all;
clc;
files=dir('*.nc');
for k=1:length(files)
ncfile=fullfile(files(k).folder, files(k).name);
SST=ncread(ncfile,'SST')
SSSanomaly = ncread(ncfile, 'SSS_anom')
SSSuncorrected =ncread(ncfile, 'SSS_uncorr')
SSS = ncread(ncfile,'SSS_corr') ;
Lat = ncread(ncfile, 'Latitude');
Lon = ncread(ncfile, 'Longitude');
Data=[Lat(:),Lon(:),SSS(:),SSSuncorrected(:),SSSanomaly(:),SST(:)];
id = (Lat>=1&Lat<=2);
Data1 = Data(id,:,:);
outputFileName= strrep(lower(ncfile),'Data1','-ASCII');
end
I attach the example of .nc file in the google drive link (only four files). Here is the example data google drive link https://drive.google.com/drive/folders/1JZehjlQWPgRbebutwnKS69gBZ_40gPCU?usp=sharing
0 Comments
Accepted Answer
Diwakar Diwakar
on 17 Sep 2023
To save each converted file as a .asc file, you can use the "save" function.
clear all;
clc;
files = dir('*.nc');
outputDirectory = 'output_asc_files';
% Create the output directory if it doesn't exist
if ~exist(outputDirectory, 'dir')
mkdir(outputDirectory);
end
for k = 1:length(files)
ncfile = fullfile(files(k).folder, files(k).name);
SST = ncread(ncfile, 'SST');
SSSanomaly = ncread(ncfile, 'SSS_anom');
SSSuncorrected = ncread(ncfile, 'SSS_uncorr');
SSS = ncread(ncfile, 'SSS_corr');
Lat = ncread(ncfile, 'Latitude');
Lon = ncread(ncfile, 'Longitude');
Data = [Lat(:), Lon(:), SSS(:), SSSuncorrected(:), SSSanomaly(:), SST(:)];
id = (Lat >= 1 & Lat <= 2);
Data1 = Data(id, :);
% Extract the filename without the extension
[~, baseFileName, ~] = fileparts(ncfile);
% Create the output .asc filename
outputFileName = fullfile(outputDirectory, [baseFileName '.asc']);
% Save the data as an ASCII file
save(outputFileName, 'Data1', '-ASCII');
end
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!