Changing numeric matrix name with the loaded file
Show older comments
Hello,
I'm very new to MATLAB and trying to write a function for my research. I have a working code as below:
load('R12_250.mat')
E50 = trapz(R12_250.IRData.Time(1:2205),R12_250.IRData.ImpulseResponse(1:2205));
E10 = trapz(R12_250.IRData.Time(1:441),R12_250.IRData.ImpulseResponse(1:441));
R12_250.mat contains two numeric arrays namely R12_250.IRData.Time and R12_250.IRData.ImpulseResponse (Please see attached R12_250.mat)
I wanted to improve the code by using uigetfile command to select other data files such as R12_500.mat, R12_1000.mat,... etc. so that I can run the code for other data sets. However the argument in trapz function needed to be changed with respect to the selected new filename. If I open R12_500.mat than the numeric matrix names in the file are R12_500.IRData.Time and R12_500.IRData.ImpulseResponse, respectively. I tried the code below but it did not work.
file = uigetfile; % This time R12_1000.mat is selected for example
[pathstr,name,ext] = fileparts(file);
load(file)
E50 = trapz(name.IRData.Time(1:2205),name.IRData.ImpulseResponse(1:2205)); %the aim of putting name variable here is to have " trapz(IR12_1000.IRData.Time(1:2205),IR12_1000.IRData.ImpulseResponse(1:2205)) " but it did not work
E10 = trapz(name.IRData.Time(1:441),name.IRData.ImpulseResponse(1:441));
Error message: Dot indexing is not supported for variables of this type (line4)
How can I solve this ?
Thank you for your help,
Sözer
1 Comment
"However the argument in trapz function needed to be changed with respect to the selected new filename."
Note that having different variable names in every MAT file makes accessing your data more complex. If the data had been designed better (with exactly the same variable names in all of those MAT files) then your code would be simpler and more robust. For example, if all of the files contained a variable named 'Data', then you would simply do this (no fiddling around with filenames or variable names is required):
S = load(file);
S.Data.IRData.Time
S.Data.IRData.ImpulseResponse
As Voss shows, you should always LOAD into an output variable (which itself is a scalar structure). The approach Voss shows is probably the most robust for that unfortunate data design, and utilises dynamic fieldnames:
Answers (1)
Voss
on 25 Feb 2023
[fn,pn] = uigetfile('*.mat','Select .mat File');
if isequal(fn,0)
return % user closed dialog without selecting a file
end
file = fullfile(pn,fn);
S = load(file);
[~,name,~] = fileparts(file);
E50 = trapz(S.(name).IRData.Time(1:2205),S.(name).IRData.ImpulseResponse(1:2205));
E10 = trapz(S.(name).IRData.Time(1:441),S.(name).IRData.ImpulseResponse(1:441));
Categories
Find more on Numerical Integration and Differentiation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!