Append indices to vector from container map

조회 수: 5 (최근 30일)
Mehdi Jaiem
Mehdi Jaiem 2022년 5월 7일
답변: Steven Lord 2022년 5월 7일
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일
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일
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일
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