Make for loop and extract data from different tables within a structure.
20 ビュー (過去 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!