Swapping entries in column of table
18 views (last 30 days)
Show older comments
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 Comment
Adam Danz
on 5 Dec 2019
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.
Accepted Answer
Adam Danz
on 5 Dec 2019
Edited: Adam Danz
on 6 Dec 2019
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
0 Comments
More Answers (1)
dpb
on 5 Dec 2019
% 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 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!