Extract data from all values of a containers.Map collection

30 ビュー (過去 30 日間)
Alon Rozen
Alon Rozen 2020 年 3 月 16 日
コメント済み: Alon Rozen 2020 年 3 月 16 日
Hi all,
Suppose I have a containers.Map key/value collection with n entries (hundreds and more). Suppose all entries have a filed ‘My_Filed’ which is an array of 1x3 doubles.
I want to create a matrix of nx3 from all these values. Of course, I can achieve this by getting all values and use a ‘for loop’ to build the matrix (with pre-allocation for speed).
My question is: is there a faster way to create this matrix?
Thanks,
Alon

採用された回答

Guillaume
Guillaume 2020 年 3 月 16 日
編集済み: Guillaume 2020 年 3 月 16 日
This doesn't involve any loop, either explicit or via any of the ***fun functions. However all the structures in the map must have identical fields and all the structures must be scalar:
allvalues = yourmap.values; %extract values, stored as a cell arrays
allvalues = vertcat(allvalues{:}); %convert cell array of N structures into a Nx1 structure array, will fail if at least one structure has different fields
fieldvalues = vertcat(allvalues.My_Filed); %extract field into a Nxm matrix. Will fail if at least one field is not the same size as the others

その他の回答 (1 件)

Mohammad Sami
Mohammad Sami 2020 年 3 月 16 日
I assume that each of value in the container is a struct with identical fields.
You can just get all the values like this
% M = containers.Map
valueSet = values(M); % this will return a cell array of structs.
My_Filed = cellfun(@(x)x.My_Filed,valueSet,'UniformOutput',false);
My_Filed = vertcat(My_Filed{:});
  2 件のコメント
Guillaume
Guillaume 2020 年 3 月 16 日
編集済み: Guillaume 2020 年 3 月 16 日
Note that cellfun is not very different from a loop. If anything, it's most likely slower than a loop due to the cost of the anonymous function call.
I would still use cellfun over an explicit loop as it's clearer at what it does.
Alon Rozen
Alon Rozen 2020 年 3 月 16 日
Thanks,
It is similar the answer I accepted - but I prefere the one without the cellfunc. These functions tends to be slower then a loop in many cases.

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

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by