Borrar filtros
Borrar filtros

For loop stores all zeros then the actual values of last iteration

20 visualizaciones (últimos 30 días)
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;

Respuesta aceptada

Walter Roberson
Walter Roberson el 3 de Dic. de 2020
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;
finalsm{k} = soilm;

Más respuestas (0)


Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by