Splitting Table Based on One Column Value
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I have a 1790x34 table of values called dP, and I would like to create two other tables based on a variable called 'A_VAL'. If the value under the 'A_VAL' variable is less than 0.1, then it is stored in the 'lo_val' table, but it is stored in the 'hi_val' table if it is greater-than or equal-to 0.1. I have tried the following code:
idx = dP(:,'A_VAL') < 0.1;
lo_val = dP(idx,:)
hi_val = dP(~idx, :)
But, unfortunately, it gives me the following error:
Error using ()
A table row subscript must be a numeric array containing real positive integers, a logical array, a
character vector, a string array, a cell array of character vectors, or a pattern scalar.
Error in Hedwig_HS_input (line 14)
lo_val = dP(idx,:)
Any assistance would be greatly appreciated, thank you!
0 commentaires
Réponse acceptée
Stephen23
le 22 Juin 2023
Modifié(e) : Stephen23
le 22 Juin 2023
Use the correct type of indexing. Curly braces returns the table content, not another table:
idx = dP{:,'A_VAL'} < 0.1;
For example:
T = array2table(rand(5,3))
Look at the class of this: is it logical? Can it be used for indexing?
idx = T(:,'Var1') < 0.5 % what you did
idx = T{:,'Var1'} < 0.5 % What you should have done, returns a logical array
You could have diagnosed this yourself: always start debugging by looking at your data. The error message tells you that the indexing array must be numeric, logical, etc... so this is where you take the initiative to learn what the class is... simply printing it out is a good start. In contrast, not looking at your data won't debug much at all.
Indexing is a MATLAB superpower: understanding the differences between curly-braces and parentheses is critical to using indexing: curly-braces gives the array content, parentheses the array itself.
The syntax you used (arithmetic/boolean operation on a table directly) always returns a table:
4 commentaires
Peter Perkins
le 17 Juil 2023
Just to add some additional clarity:
In older versions of MATLAB, the following comparison would be an error. In recent versions (R2023a), it works:
T = array2table(rand(5,3));
Tidx = T(:,'Var1') < 0.5
But as Stephen23 says, the result is a table, because the presumption is that you have all your data in a table so you must want to stay in a table. Stephen23 describes how to extract a numeric, on which < returns a logical, but it's also possble to do the above and then
Tidx.Var1
Either is fine, which is better depends what you are doing.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!