For loop stores all zeros then the actual values of last iteration
22 次查看(过去 30 天)
显示 更早的评论
Hello,
Whenever i try to run my code, it only saves the last values of the loop and all others are saved as zeros so im left with 165 x 243 array that only has the last column with the actual values that I need to use while everything else is a zero.
The first sections of my code are me processing the data to remove bad quality values, i have tested this part on some indiviudal files in the folder that the code is looping through and it works perfectly fine, so the problem must lie in the last part of the loop that is supposed to store the iteration values.
I'm still a beginner so sorry if this is unclear/dumb question, thanks!
dir_to_search = '/Users/..../3302';
folder = dir('*.txt');
n = length(folder);
k = 0;
for i = 1:length(folder)
filename = fullfile(dir_to_search, folder(i).name);
k = k + 1;
file = readtable(filename);
% extracting the raw data and qc flags
sm = file(5:end,8);
temp = file(5:end,9);
qc = file(5:end,end);
data = [sm,temp,qc];
data_daily = table2array(data);
% temp qc part
index = data_daily(:,2) < 4;
a = data_daily(:,1);
a(index) = NaN;
data_daily = a;
b = array2table(a);
x = [b,qc];
x = table2array(x);
% flag qc part
indx = x(:,2) > 0;
x(indx) = NaN;
% trying to store the values (WHERE THE PROBLEM IS)
finalsm = zeros(height(x),1); % 'height(x)' bc array changes size each iteration
soilm = x(:,1);
finalsm(:,k) = soilm;
end
0 个评论
采纳的回答
Walter Roberson
2020-12-3
Your statement
finalsm = zeros(height(x),1); % 'height(x)' bc array changes size each iteration
is throwing away all previous output.
If your output can be different sizes for different iterations then use a cell array:
Before the loop:
finalsm = cell(length(folder), 1);
Inside the loop, do not assign zeros to finalsm, and change
finalsm(:,k) = soilm;
to
finalsm{k} = soilm;
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!