vector to struct without loop

2 ビュー (過去 30 日間)
Fernando
Fernando 2017 年 1 月 1 日
コメント済み: Fernando 2017 年 1 月 2 日
I have two vectors, one with ids and another with information for each id. For each id, the vector with information has, potentially, a different number of entries. I want to assign this to a struct, ideally without using a loop as the information vector/struct is used within an optimization routine and it changes every time there is a new iteration.
This is the example:
id=[1 1 1 2 2 3]';
info = [0.5 1 10 1 0.3 -200]';
In this case, id 1 has three elements in the information vector, id 2 has two, and id 3 has one. With the loop, I would do
for i = 1:max(id),
m(i).info = info(id==i);
end
Is there anyway to do this without using the loop?
Thanks

採用された回答

Walter Roberson
Walter Roberson 2017 年 1 月 1 日
t1 = [find(diff(id).'), length(id)];
t2 = [t1(1), diff(t1)];
m = struct('info', mat2cell(info, t2, 1));
  2 件のコメント
Fernando
Fernando 2017 年 1 月 1 日
This is great, thanks!
Matt J
Matt J 2017 年 1 月 1 日
Note, there are for-loops inside mat2cell.m.

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

その他の回答 (2 件)

Matt J
Matt J 2017 年 1 月 1 日
I'm not sure there's a fast way without loops, but here's a way that at least doesn't use any Mcoded for-loops as far as I know
n=max(id);
data=accumarray(id,info,[],@(x){x});
[m(1:n).info]=deal(data{:});
  1 件のコメント
Fernando
Fernando 2017 年 1 月 2 日
Thanks for the suggestion. In my application, with id going from 1 to ~30,000, this was slightly slower than the first approach, but both significantly faster than my Mcoded for-loop.

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


Fernando
Fernando 2017 年 1 月 2 日
Thanks for both suggestions, I have it working now.
Out of curiosity, how would I go the other way around? If I had the the information in structs of different dimensions for each id and I wanted to go from the structs to the vector info?
Thanks.
  2 件のコメント
Matt J
Matt J 2017 年 1 月 2 日
info = vertcat(m.info);
Fernando
Fernando 2017 年 1 月 2 日
this is great, thanks.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by