- Identify the index values for rows containing -1000 and those with other values.
- Generate pointers corresponding to the index values determined in step 1.
- Examine the array values and populate the table rows accordingly.
Sorting Matrix where column specifies condition next element needs to meet
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello,
Say I have a long table with elements and an array
% table with distinct elements for A1. A2 is sometimes an integer and
% sometimes -1000
T A1 A2
0 182 181
1 182 180
2 181 180
3 45 -1000
4 29 -1000
% array specifies whether A2 should have -1000
[True False True False False]
Separately, i have an array that specifies a different order for when -1000 (in A2) needs to be present.
so for the example above the desired output is :
T A1 A2
0 45 -1000 % array is true and first time -1000 appears
1 182 181 % array above is false
2 29 -1000 % second time -1000 appears
3 182 180
4 181 180
Any efficient ways to do this?
Your help will be greatly appreciated!
댓글 수: 0
답변 (1개)
Arun
2024년 2월 23일
Hi Levi,
I understand that the objective is to sort the table in accordance with the value present in an array. A logical true value indicates that the table row should have value -1000. I assume that the number of rows with -1000 values and true value in the array are equal.
The following steps helps in achieving the desired outcome:
Here is the code that helps to attain the desired output:
T = [0; 1; 2; 3; 4];
A1 = [182; 182; 181; 45; 29];
A2 = [181; 180; 180; -1000; -1000];
initialT = table(T, A1, A2);
array = logical([true false true false false]);
%find the rows with -1000 values
indexm1000 = find(initialT.A2 == -1000);
indexNot = setdiff([1:height(initialT)],indexm1000);
%pointers to track the order of -1000 and non -1000 rows
iindexm1000 = 1;
iindexNot = 1;
finalT = table(); % empty table to store the values in the required order.
%check if true place the row with -1000 value
for i = array
%if true insert the row with -1000 value
if(i)
finalT(end+1,:) = initialT(indexm1000(iindexm1000),:);
iindexm1000 = iindexm1000 +1;
else
finalT(end+1,:) = initialT(indexNot(iindexNot),:);
iindexNot = iindexNot +1;
end
end
disp(finalT);
For more information related to table please refer the documentation link: https://www.mathworks.com/help/matlab/tables.html
HTH
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!