How can I load .mat files?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hello, I have 3 .mat files and I want to measure feature importance. Following code works fine with .txt files but I am getting an error message with .mat files. I want to load all .mat files one by one and seperate predictors (X) and response variable (Y, the last column) for "fscchi2" function but I can't. How can I fix it?
matFiles = dir('Datasets/*.mat');
nFiles = length(matFiles);
for i = 1:nFiles
DataSet = load(matFiles(i).name);
X = DataSet(:,1:end-1);
Y = DataSet(:,end);
[~,Scores] = fscchi2(X,Y);
end
4 Kommentare
Stephen23
am 18 Okt. 2021
Bearbeitet: Stephen23
am 18 Okt. 2021
"I couldn't find a way to seperate response column like I did with the .txt files"
The columns are in the structure field, not the structure itself. So you just need to access its field/s. If the fieldnames change (i.e. the data is very badly designed by someone who wants to make your life harder) then you can use dynamic fieldnames:
Rik showed this below.
Avoid loading directly into the workspace (as you show) unless you want to include latent bugs in your code.
Much simpler and more robust code would result if the data had been better designed (i.e. the same variable/field name).
Akzeptierte Antwort
Rik
am 18 Okt. 2021
Or:
matfilenames={'Datasets/a.mat','Datasets/b.mat','Datasets/c.mat'};
for k = 1:3
S=load(matfilename{k});
fields=fieldnames(S);
data=s.(fields{1});
X = data(:,1:end-1);
Y = data(:,end);
[~,nCols] = size(X);
[Idx,Scores] = fscchi2(X,Y);
...
end
Next time, try to give the variables in your mat files the same name, so you can load to a struct array.
6 Kommentare
Star Strider
am 18 Okt. 2021
I provided something substantially similar to that, however never received any feedback on what did or didn’t work, why it didn’t work, or anything else. I deleted my answer when it became obvious that my efforts were apparently futile.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Live Scripts and Functions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!