Azzera filtri
Azzera filtri

pass a struct through a loop to extract data and have the i in the loop added to the name

2 visualizzazioni (ultimi 30 giorni)
The objective is at the bottom of this code, and it is to run a loop over structs, to read each one, apply an if statement and then to update the accuracy totals like a counter. The goal is the to open the accuracy struct, and see a column of accuracies with the total number of correct. The issue lies in the last nested for loop, where i want the i to be added to the struct cell name. For example, in the first iteration, accuracy_total_i would be accuracy_total_1. How do i add the i to the name?
clc; clear; close all
path = 'some_path';
accuracy_files = dir(fullfile(path, 'accuracy*'));
pred_files = dir(fullfile(path, 'pred*'));
for i = 1:length(accuracy_files)
temp = strcat('accuracy_', num2str(i));
accuracy.(temp) = readtable(fullfile(path, accuracy_files(i).name));
end
for i = 1:length(pred_files)
temp = strcat('pred_', num2str(i));
predictions.(temp) = readtable(fullfile(path, pred_files(i).name));
end
scores = readtable('other_path');
n_known = scores.known(1);
n_unknown = scores.unknown(1);
N = n_known + n_unknown;
times = scores.time_elapsed;
for i = 1:length(pred_files)
temp = strcat('accuracy_total_', num2str(i));
accuracy_totals.(temp) = 0;
end
for i = 1:length(pred_files)
for j = 1:length(n_unknown)
if predictions(1).pred_i.y_pred(j) == predictions(1).y_all(j)
accuracy_totals(1).accuracy_total_i = accuracy_totals(1).accuracy_total_i +1
end
end
end

Risposta accettata

Jan
Jan il 11 Feb 2023
Modificato: Jan il 11 Feb 2023
The best idea is to use an index as index:
accuracy_totals(1).accuracy_total(i)
Arrays are smarter than a pile of fields with an index hidden in the name.
Less efiicient, but working: "dynamic field names":
accuracy_totals(1).(sprintf('accuracy_total_%d', i))

Più risposte (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov il 11 Feb 2023
Here is one of the viable codes to read series of data and store in a structure array:
path = 'C:\...' % Specify the path
for ii=1:100 % How many data file to be imported
textFileName = ['accuracy' num2str(ii) '.csv']; % accuracy1.csv, accuracy2.csv, ...
% textFileName = ['accuracy' num2str(ii) '.txt']; % accuracy1.txt, accuracy2.txt, ...
% textFileName = ['accuracy' num2str(ii) '.dat'];
% textFileName = ['accuracy' num2str(ii) '.xlsx'];
if isfile(textFileName)
temp = strcat('accuracy_', num2str(ii));
accuracy.(temp) = readtable(fullfile(path, textFileName)); % Stores the read data in a structure called: accuracy
else
fprintf('File %s does not exist.\n', textFileName);
end
end

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by