How can I save structures from a cellarray into individual .mat files with a loop?
Afficher commentaires plus anciens
I want to be able to change a whole folder of a dataset all at once in the same way, just with an extension of the given names of the files and save it in a new folder. To read and process the data I don't have any Problem. But when I'm using the code as below (4.), each generated file contains all the informations. e.g. A contains only the infromations of A, but A_cut contains the processed information of the prepared A and B.
Below you find my code:
- Is for generating what my data looks like.
- Is How I read all of the folders in one cell array without loosing any information
- is to prepare them
- is where I don't know what the Problem is.
clear all
% 1.Create data (according to the data i'm actually using)
A.spc=rand(100,1);
A.wavenumber=[1:100].';
A.header={'first','second','third'}.';
B.spc=rand(100,1);
B.wavenumber=[1:100].';
B.header={'first','second','third'}.';
%save the data as file
save('A.mat','A')
save('B.mat','B')
%% 2.read data
clear all
clc
location=uigetdir;
info=dir([location,'\*.mat']);
filenames={info(:).name};
data=cell(length(info),1);
for i=1:length(info)
fullname=[location,'\',info(i).name];
data{i}=importdata(fullname,'\t',14,0);
end
%% 3.data procession
datacut=data; %for header information
for j = 1:length(data)
datacut{j,1}.wavenumber = data{j,1}.wavenumber(j, :);
datacut{j,1}.spc = data{j,1}.spc(j, :);
end
%% 4.save data
savepath=uigetdir(cd,'Save to folder');
str_affix = inputdlg('Enter string affix:','String Affix',[1 50],{'cut'});
for i = 1:length(data)
c_string=string(strcat(savepath,'\',erase(info(i).name,'.mat'),'_',str_affix,'.mat'));
save(c_string, 'datacut');
end
3 commentaires
Rather then concatenating strings:
c_string=string(strcat(savepath,'\',erase(info(i).name,'.mat'),'_',str_affix,'.mat'));
it is recommended to use fullfile:
[~,name] = fileparts(info(i).name);
name = sprintf('%s_%s.mat',name,sffx);
name = fullfile(savepath,name);
Stebe Hauser
le 21 Mai 2019
Modifié(e) : Stebe Hauser
le 21 Mai 2019
The output of inputdlg is a cell array, so you will need to use cell indexing to get the content of the first cell:
name = sprintf('%s_%s.mat',name,str_affix{1});
% ^^^ content of first cell
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!