Make for loop and extract data from different tables within a structure.
19 次查看(过去 30 天)
显示 更早的评论
Could you help me cxtract data from different tables in loops?
Samples are separated into separate csv files with 4 columns of data. Each of the columns in a file has the same number of rows but the number of rows in different files differs.
clc;clear;
%% Call Samples
n=18; %Number of specimens/ samples
for i=1:n
n_strPadded = sprintf('%02d',i); %if files contain leading zeros (mine does)
fname = ['Sample' n_strPadded] %File name as string
temp_var = strcat('Sample',num2str(i)); %Trying to convert file name from a string to to a variable
Samples.(temp_var)=readtable(fname); %convert csv files into tables and import them.
end
% now each csv file (each sample data is located within a table within a
% structure. Sample1, Sample2,.... in structure Samples
%I want to extract data from the tables by indexing it like
%Samples(i).Sample(i) , where samplei is a table (from within the
%structure). Then the following steps could be completed once in a loop.
%I have tried to use some commands to call out a table without using the
%tables unique name (below). The only way I have been able
%to do this is Samples.Samplex.var (x= sample # and var is the variable or
%column name) or Samples.Samplex(m,n).
%{
for i=1:n
T1=Samples(i)
end
C=struct2cell(Samples)
x=C(1)
x=Samples(2).Sample(2,2)
%}
%% Stress Sample 2
Cross_sectionalArea=readtable('Cross_sectionalArea.csv');
StressSample2=Samples.Sample2.Force*(10^3) / Cross_sectionalArea.m(2);
%% Strain Sample 2
StrainSample2=Samples.Sample2.Strain1;
%% Plot Stress Strain Sample 2
plot(StrainSample2,StressSample2)
0 个评论
采纳的回答
Stephen23
2020-10-7
编辑:Stephen23
2020-10-7
You are confusing the field names with an index, but really you should just be using an index. Rather than awkward messing about with dynamic fieldnames in a scalar structure, you would be much better off using basic efficient indexing with a cell array:
n = 18;
c = cell(1,n);
for k = 1:n
fname = sprintf('Sample%02d',k);
c{k} = readtable(fname); % or READMATRIX
end
Storing the imported data in a simple cell array is exactly what the MATLAB documentation recommends:
0 个评论
更多回答(1 个)
Ayush Gupta
2020-10-7
The excel files here can be read directly with the help of readmatrix function. Suppose there is an excel file of name abc.xlsx, the file can be read, and first column can be stored as follows
data = readmatrix('abc.xlsx');
dolumn1 = data(:,1)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Analysis 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!