Append indices to vector from container map

4 visualizzazioni (ultimi 30 giorni)
I have the above mentioned issue when I try to run this code:
I create the following container map "M" from the datastructure DS
keys = {DS.UserNum}; #UserNum
valueSet = {DS.CarNum}; #Contact_Num
M = containers.Map(keys,valueSet)
UserNum Contact_Num
1 [2 4]
2 5
3 [1 2 4]
4 [2]
5 []
Without the need for a for-loop or the initial data structure DS, I want to create a vector containing user numbers which have been in contact with UserNum 2 (in this case we will have vector containing 1,3 and 4).
Best :)

Risposta accettata

Walter Roberson
Walter Roberson il 7 Mag 2022
That cannot be done in MATLAB under the restrictions you put on.
containers.map does not offer any operations that affect all key/value pairs.
You can hide the for loop with cellfun, but a loop still has to be present at some level.
Side note: if you were to use digraph() objects there would be built-in support for this kind of query.
  3 Commenti
Mehdi Jaiem
Mehdi Jaiem il 7 Mag 2022
I tried the following manipulation but it did not work
b = 100001;
out = cellfun(@(x) ismember(b, cell2mat(x)), valueSet);
Walter Roberson
Walter Roberson il 7 Mag 2022
present = cellfun(@(x)ismember(b, x), values(M));
keylist = keys(M);
found_at = keylist(present);

Accedi per commentare.

Più risposte (1)

Steven Lord
Steven Lord il 7 Mag 2022
Like Walter suggested I'd use a digraph for this sort of operation. You can build a digraph from your containers.Map object. Let's start off with the containers.Map object.
cm = containers.Map('KeyType', 'double', 'ValueType', 'any');
cm(1) = [2 4];
cm(2) = 5;
cm(3) = [1 2 4];
cm(4) = 2;
cm(5) = [];
Now each key-value pair becomes some of the edges in the digraph.
D = digraph;
thekeys = keys(cm);
for whichkey = 1:length(cm)
k = thekeys{whichkey};
D = addedge(D, k, cm(k));
end
plot(D)
Now the answer to your question, who's been in contact with person 2, is the predecessors of 2 in the digraph.
P = predecessors(D, 2)
P = 3×1
1 3 4
You could also recreate the containers.Map object from the digraph.
cm2 = containers.Map('KeyType', 'double', 'ValueType', 'any');
for n = 1:numnodes(D)
cm2(n) = successors(D, n);
end
% check
cm2(3)
ans = 3×1
1 2 4
cm2(5)
ans = 0×1 empty double column vector

Community Treasure Hunt

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

Start Hunting!

Translated by