pass a struct through a loop to extract data and have the i in the loop added to the name
3 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
更多回答(1 个)
Sulaymon Eshkabilov
2023-2-11
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Repeated Measures and MANOVA 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!