【问题标题】:How can I loop through and process files from a directory individually?如何单独循环和处理目录中的文件?
【发布时间】:2021-03-11 15:33:54
【问题描述】:

我正在尝试编写一个函数,它迭代地循环遍历目录中的一堆 .txt 文件并单独处理它们。处理完文件后,我想绘制输出变量,然后在下一次迭代中将新变量绘制在同一张图上。我的代码如下所示,但似乎不起作用,它返回一个在调用 function2 期间未分配的“输出参数 'output1'(可能还有其他)。

目前我的代码如下所示:

function [output1, output2, fig] = Processing(Folder_1,Folder_2,Folder_3)
%% Read in all the Data

% Initialise Loop to process each file independently
for i = 1 : length(Text_Files1)

Sorted_Index1 = Indices1(i);
Path1 = fullfile(Folder_1,Text_Files1(Sorted_Index1).name);
Table1 = readtable(Path1);

Sorted_Index2 = Indices2(i);
Path2 = fullfile(Folder_2,Text_Files2(Sorted_Index2).name);
Table2 = readtable(Path2);

Sorted_Index3 = Indices3(i);
Path3 = fullfile(Folder_3,Text_Files3(Sorted_Index3).name);
Table3 = readtable(Path3,'Delimiter',';');

%% Process Data through the Loop
[HR] = function1(processed_data)

[output1 output2] = function2(HR, Time);
hold on
fig = figure('Visible', false);
subplot(10,10,1:90)
plot(output2, output1, 'Color', [0.92 0.47 0.44], 'LineWidth', 1.5);
end
end

%% 函数二:

function [output1, output2] = function2(t, y, z)

segment = 1:z:max(y);

% Iterate through each time segment and calculate average t value
for x = 1:length(segment)-1
    
        SegmentScores = find(y > segment(x) & ...
        y < segment(x+1));
    
    output1(x) = mean(y(SegmentScores));
    
    output2(x) = Segment(x+1); 
    
end

end

【问题讨论】:

  • 请仅提供minimal example
  • 已经把它剪掉了一点,希望有道理!
  • 好多了。另一方面,该错误意味着在您的 function2 内部您没有设置任何输出;如果不查看该功能,则无法为您提供帮助。
  • 如果我将 i 设置为 1,则 function2 工作正常并按预期输出结果,只是每当我尝试在循环中迭代它时都会遇到错误
  • 在function2中添加,两个输出都设置在其中,这就是为什么我无法理解错误

标签: matlab


【解决方案1】:

问题是你用两个输入调用function2(HR, Time),而它需要三个function2(t, y, z)

因此,我假设 function2 segment 内部是一个空数组,因此根本没有输入循环 for x = 1:length(segment) - 1

由于output1output2 的定义仅在循环内部,因此永远不会创建它们,因此会出现错误。

如果您向function2 提供三个输入,则问题将得到解决。请注意您提供它们的顺序(例如,我假设您的Time 输入应该与函数中的t 相同,因此它应该是要传递的第一个输入)。

【讨论】:

  • 如果有帮助,请考虑接受此答案。
猜你喜欢
  • 1970-01-01
  • 2013-04-24
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
相关资源
最近更新 更多