How to create a table with an if statement

8 visualizzazioni (ultimi 30 giorni)
Giada
Giada il 13 Giu 2023
Modificato: Samay Sagar il 14 Giu 2023
I'm trying to create a new table (here called: BL_subtraction) with values (1 and 0) indicating whether a certain phenomena (value from previous table SmoothData_hampel is above threshold or not) is present.
Here's the code that I'm using:
BL_subtraction=table
for ii = 1:1:numOfCols
Mean=horzcat('Mean',num2str(ii)); %create a char allowing easy identification of the variable in all the tables
BL_min=min(SmoothData_hampel.(Mean)); %identifies the mean (for each column) in SmoothData_hampel
Signal_aboveBL=1.2*BL_min % defines threshold
for jj=1:1:numOfRows
if table2array(SmoothData_hampel(jj,ii))>=Signal_aboveBL
Table1(jj,ii)=1; %assignes 1 if data form SmoothData_hampel is above threshold
else
Table1(jj,ii)=0; % otherwise 0
end
end
BL_subtraction=[ BL_subtraction array2table(Table1,'VariableNames',{(Mean)})]; %create a table with 1 and 0
end
Things are ok for the first loop, but as soon as I need to add a second column to BL_subtraction my code isn't working. Matlab gives the following output: "Error using array2table. The VariableNames property must contain one name for each variable in the table."
I'm new to matlab and I cannot get my head around it... form 2 days already. Working with Matlab R2020b

Risposte (2)

Cris LaPierre
Cris LaPierre il 13 Giu 2023
Modificato: Cris LaPierre il 13 Giu 2023
You create BL_subtraction as an empty array, and then try to concatenate to it. That is giving you the error, since the two tables you are trying to combine do not have the same number of rows.
You can use logical indexing to create your array of 0s or 1s, and then table indexing to assign the resulting vector to a variable in your table. See the Access Data in Tables page for details on the various ways to do this. Maybe something like this
for ii = 1:1:numOfCols
Mean=horzcat('Mean',num2str(ii)); %create a char allowing easy identification of the variable in all the tables
BL_min=min(SmoothData_hampel.(Mean)); %identifies the mean (for each column) in SmoothData_hampel
Signal_aboveBL=1.2*BL_min % defines threshold
BL_subtraction.(Mean) = SmoothData_hampel.(Mean)>=Signal_aboveBL
end

Samay Sagar
Samay Sagar il 13 Giu 2023
Modificato: Samay Sagar il 14 Giu 2023
The above error is occuring because Table1 has ii columns but when you are concatenating it with BL_subtraction table , you are only providing name for 1 column. To use array2table function you need to provide names for all columns. So you will need to pass an array of names of size ii instead of only passing {Mean}.

Categorie

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

Community Treasure Hunt

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

Start Hunting!

Translated by