Accessing elements in a structure

조회 수: 2 (최근 30일)
C.G.
C.G. 2021년 7월 27일
편집: Stephen23 2021년 7월 27일
I have 2 matlab files, both containing 2 elements: velocity and points.
i have loaded these two files into a structure, but now I want to access each individual field in the velocity column and do some calculations in it (e.g. work out the mean value).
I am struggling to access each field, could anybody help me please?
file = dir('*.mat');
num_files = length(file);
[~, index] = natsort({file.name});
filelist = file(index);
out = load(filelist(1).name);
for k = 1:numel(filelist)
out(k) = load(filelist(k).name);
end
  댓글 수: 1
Stephen23
Stephen23 2021년 7월 27일
편집: Stephen23 2021년 7월 27일
Unless you have a good reason for using NATSORT you should probably use NATSORTFILES:
which lets you write simpler code by directly sorting the output from DIR:
P = 'absolute or relative filepath to where the files are saved';
S = dir(fullfile(P,'*.mat'));
S = natsortfiles(S); % <------- much simpler!
for k = 1:numel(S)
F = fullfile(P,S(k).name)
... etc
end

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2021년 7월 27일
편집: KSSV 2021년 7월 27일
file = dir('*.mat'); %fine all the .mat files
num_files = length(file); %record how many files have been found
[~, index] = natsort({file.name}); %sort the files into order
filelist = file(index);
GTav = zeros(numel(filelist),1)
for k = 1:numel(filelist)
load(filelist(k).name); % I hope the structure is named out in every file
% For each cell in the velocity column of the structure
v1 = vel ;
%1. calculate the resultant velocity of each particle
ResV = sqrt((v1(:,1).^2) + (v1(:,2).^2) + (v1(:,3).^2));
%2. calculte the mean resultant velocity of all the particles
ResVav = mean(ResV);
%3. calculate the granular temperature of all the particles
GT = ResV-ResVav;
%4. calculate the average granular temperature for each field
GTav(k) = mean(GT);
end
  댓글 수: 10
C.G.
C.G. 2021년 7월 27일
Thank you so much for your help.
Stephen23
Stephen23 2021년 7월 27일
편집: Stephen23 2021년 7월 27일
Note that KSSV's answer loads directly into the workspace, which is not recommended.
You can make your code more robust by loading into an output variable (which is a scalar structure):
out = load(..);
out.vel

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by