Swapping entries in column of table

조회 수: 11 (최근 30일)
Deepa Maheshvare
Deepa Maheshvare 2019년 12월 5일
편집: Adam Danz 2019년 12월 6일
I've the following table and I want to swap the entries
tbl = table({'1', '2'; '2', '3'; '2', '3'; '3', '4'},'VariableNames', {'multicol'});
i_pts = 2;
for i = i_pts
searchval = num2str(i);
temp_tbl = tbl(any(strcmp(tbl.multicol, searchval), 2), :);
end
temp_tbl
Obtained output:
multicol
______________
{'1'} {'2'}
{'2'} {'3'}
{'2'} {'3'}
I'd like to obtain the following from the above output.
multicol
______________
{'2'} {'1'}
{'2'} {'3'}
{'2'} {'3'}
Any suggestion on how on this can be done?
  댓글 수: 1
Adam Danz
Adam Danz 2019년 12월 5일
Deepa Maheshvare's answer moved here as a comment
Sorry for not being clear. The rule is if the value saved in variable, i_pts, is present in first column of the multicolum table no swapping is required. If the value is present in second column then swapping is performed. For instance, in the example posted in the first answer to this question 2 is present in second column in the first row. So swapping is required. In the second and third rows 2 is present in column 1 of the table. So no swapping is required.
Likewise in the second post, 3 is the value stored in i_pts. First two rows of the table contain 3 in the second column. So swapping is required.

댓글을 달려면 로그인하십시오.

채택된 답변

Adam Danz
Adam Danz 2019년 12월 5일
편집: Adam Danz 2019년 12월 6일
I'm not sure why you're using string characters instead of numbers but I'll assume you have a reason for that. Here's how to identify the rows of tbl.multicol where the second column contains the character representation of i_pts (which is numeric). Then flip those rows.
rowsToSwitch = strcmp(tbl.multicol(:,2),num2str(i_pts)); %logical vector identifying rows to flip
tbl.multicol(rowsToSwitch,:) = fliplr(tbl.multicol(rowsToSwitch,:)); % Flip those rows

추가 답변 (1개)

dpb
dpb 2019년 12월 5일
% first build a more workable table arrangement...
t=table(str2double(tbl.multicol),'VariableNames',{'array'});
t=t(1:3,:)
t =
3×1 table
array
______
1 2
2 3
2 3
>>
% Rearrange rows with match of second in first column
ix=ismember(t.array(:,2),t.array(:,1));
t.array(ix,:)=flip(t.array(ix,:));
results in
>> t =
3×1 table
array
______
2 1
2 3
2 3
>>
  댓글 수: 3
dpb
dpb 2019년 12월 5일
You haven't clearly defined the rule behind the desire...
Adam Danz
Adam Danz 2019년 12월 5일
I also have no idea what the rule is.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by