Splitting Table Based on One Column Value
    조회 수: 21 (최근 30일)
  
       이전 댓글 표시
    
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
채택된 답변
  Stephen23
      
      
 2023년 6월 22일
        
      편집: Stephen23
      
      
 2023년 6월 22일
  
      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
  Peter Perkins
    
 2023년 7월 17일
				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.
추가 답변 (0개)
참고 항목
카테고리
				Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



