The following contents are stored in a table, in variable 'tbl',
Multico value
______________
{'1'} {'2'} 1
{'2'} {'3'} 2
{'3'} {'4'} 1
{'4'} {'5'} 2
I would like to do the following,
variable = 2,
If the variable is present in tbl.Multico, I would like to retain only those rows and delete the remining rows.
Example,
Multico value
______________
{'1'} {'2'} 1
{'2'} {'3'} 2
Also, if variable is present in column 2 of Multico, the value in column 2 of tbl will remain unchanged. If the variable is
in column 1 of Multico the sign of the value in column2 of tbl will change.
Th expected output is,
Multico value
______________
{'1'} {'2'} 1
{'2'} {'3'} -2
I'd like to ask for suggstions on how this can be done.
Is there a function similar to python's groupby for filtering contents of a table?

 Accepted Answer

Any reason why Multico is a cell array? If all the cells are just scalar, then it's a waste of memory and complicates the code for no good reason.
So first step, convert that cell array into a 2 column matrix:
yourtable.Multico = cell2mat(yourtable.Multico);
Your filtering is then trivially done:
serchval = 2;
newtable = yourtable(any(yourtable.Multico == searchval, 2), :)
If you then want to change the sign of value when searchval is in first column of Multico:
tochange = newtable.Multico(1, :) == searchval;
newtable.value(tochange) = -newtable.value(tochange)

4 Comments

Many thanks for the response.
Any reason why Multico is a cell array?`
Yes, the table has ben created in the following way.
t = 1:4;
h = 2:5;
G = graph(t,h);
I've tried to name the nodes of the graph,
G.Nodes.Name = cellstr(string(1:height(G.Nodes))');
tbl = G.Edges
Gives the above table.
cell2mat(tbl.Multico) gives
4×2 char array
'12'
'23'
'34'
'45'
Oh! I completely overlooked that you were storing char vectors and not numbers in Multico.
However, I must ask why? Why don't you stick with numeric node numbers instead of naming them?
Anyway, if you stick with a cell array of char vectors, then it's not much more complicated, just replace the == by a call to strcmp:
%no longer converting cell array to matrix since it contains char vectors.
serchval = '2';
newtable = yourtable(any(strcmp(yourtable.Multico, searchval), 2), :)
tochange = strcmp(newtable.Multico(1, :), searchval);
newtable.value(tochange) = -newtable.value(tochange)
Thanks a lot. However, I get the following error.
The logical indices contain a true value outside of the array bounds.
Is it because we are trying to index with [0 1] stored in tochange (newtable.value(tochange))?
Answering you question,
Why don't you stick with numeric node numbers instead of naming them?
I want to access the nodes for deleting and adding edges. I am not sure how to access the nodes without names.
It works!!

Sign in to comment.

More Answers (0)

Products

Release

R2019b

Tags

Community Treasure Hunt

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

Start Hunting!