Convert and save multiple .nc file into .asc by keeping the original filename

조회 수: 2 (최근 30일)
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

채택된 답변

Diwakar Diwakar
Diwakar Diwakar 2023년 9월 17일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 SPICE files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by