Swapping entries in column of table

11 Ansichten (letzte 30 Tage)
Deepa Maheshvare
Deepa Maheshvare am 5 Dez. 2019
Bearbeitet: Adam Danz am 6 Dez. 2019
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 Kommentar
Adam Danz
Adam Danz am 5 Dez. 2019
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Adam Danz
Adam Danz am 5 Dez. 2019
Bearbeitet: Adam Danz am 6 Dez. 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

Weitere Antworten (1)

dpb
dpb am 5 Dez. 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 Kommentare
dpb
dpb am 5 Dez. 2019
You haven't clearly defined the rule behind the desire...
Adam Danz
Adam Danz am 5 Dez. 2019
I also have no idea what the rule is.

Melden Sie sich an, um zu kommentieren.

Tags

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by