How can I save structures from a cellarray into individual .mat files with a loop?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
Bob Thompson
2019년 5월 20일
It is saving all of the data because you are not indexing your save selection.
save(c_string,'datacut');
You will need to create a temporary variable which contains just the desired cell, as you cannot index in the save command directly.
tmp = datacut{:};
save(c_string,'tmp')
댓글 수: 3
Stephen23
2019년 5월 21일
편집: Stephen23
2019년 5월 21일
"... but when you compare A_cut.mat with B_cut.mat there are the same values."
Sure, because within the loop the data that you refer to is exactly the same on each loop iteration. In fact you told MATLAB to take the content of the first cell of datacut:
tmp = datacut{:};
% ^^^ comma separated list.
%^^ first cell's content.
You will need to use indexing to access a different cell's data on each loop iteration, e.g.:
tmp = datacut{i};
% ^ loop index
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!