Make for loop and extract data from different tables within a structure.
조회 수: 54 (최근 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에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!