フィルターのクリア

Multi Struct to Matrix

1 回表示 (過去 30 日間)
Jack
Jack 2016 年 2 月 18 日
コメント済み: Stephen23 2017 年 10 月 31 日
From Structs of Arrays:
s(1).x = [1 2 3; 4 5 6; 7 8 9];
s(2).x = [11 12 13; 14 15 16; 17 18 19];
I would like to get a matrix made up of, say, the second rows only - without using a loop
ans = [4 5 6; 14 15 16]
But typing
s.x(2,:) or [s.x(2,:)] or {s.x(2,:)}
gives the error
"Expected one output from a curly brace or dot indexing expression, but there were 2 results."
Any help appreciated. Jack
  2 件のコメント
Stephen23
Stephen23 2016 年 2 月 18 日
編集済み: Stephen23 2016 年 2 月 18 日
I am not sure that those attempted syntaxes would make much sense anyway...
s.x
actually creates a comma separated list, like this:
s(1).x, s(2).x, ... s(end).x
It makes no sense to apply indexing to the last variable in a comma separated list:
A,B,C,D(:,2)
and then expect that the indexing is applied to all variables within the comma separated list. This would be counter-intuitive. The only logical place would be after the square brackets/curly braces, in which case this becomes a standard application of indexing into a single temporary variable, like this:
[s.x](:,2)
This is an enhancement that many people would like, but so far has not yet been implemented.
Jack
Jack 2016 年 2 月 18 日
Makes sense. I voted up Walter's proposal.

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

回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 2 月 18 日
cell2mat( arrayfun(@(c) c.x(2,:), (1:length(s)).', 'Uniform', 0) )
  8 件のコメント
Ben Oeveren
Ben Oeveren 2017 年 10 月 31 日
Thank you good idea. Just tested the eval on timing. The difference in time is not really big.
For 106 fields, in total a double of 10883839x3 Elapsed time is 14.001423 seconds. eval Elapsed time is 13.644880 seconds. normal loop
Nevertheless, getfield and setfield seems like good alternative solution.
Stephen23
Stephen23 2017 年 10 月 31 日
@Ben Oeveren: consider not just just the simple timing in a loop, but also that JIT does not work, debugging tools do not work, variable highlighting does not work, the security risk, etc.
And thinking that "my code does not need to be secure" is exactly why doing this is so easy:

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


Jan
Jan 2016 年 2 月 18 日
編集済み: Jan 2016 年 2 月 18 日
Walter's suggestion is compact and nice. Internally this contains loops also. So the actual problem I would solve is this:
... without using a loop
Create a loop, care for a proper pre-allocation, export this to a secific M-function if you want to keep you main program clean and lean.
  1 件のコメント
Jack
Jack 2016 年 2 月 18 日
I see. Braces would seem intuitive: would be nice to have such functionality in the future if possible...

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

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by