Append indices to vector from container map

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 :)

 採用された回答

Walter Roberson
Walter Roberson 2022 年 5 月 7 日

1 投票

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 件のコメント

Mehdi Jaiem
Mehdi Jaiem 2022 年 5 月 7 日
Yes a possible solution with cellfun is still possible in my case. What function or logic could be useful if I had to use it?
Mehdi Jaiem
Mehdi Jaiem 2022 年 5 月 7 日
I tried the following manipulation but it did not work
b = 100001;
out = cellfun(@(x) ismember(b, cell2mat(x)), valueSet);
Walter Roberson
Walter Roberson 2022 年 5 月 7 日
present = cellfun(@(x)ismember(b, x), values(M));
keylist = keys(M);
found_at = keylist(present);

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 5 月 7 日

1 投票

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

カテゴリ

ヘルプ センター および File ExchangeHandle Classes についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by