Multi Struct to Matrix

11 views (last 30 days)
Jack
Jack on 18 Feb 2016
Commented: Stephen23 on 31 Oct 2017
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 Comments
Jack
Jack on 18 Feb 2016
Makes sense. I voted up Walter's proposal.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 18 Feb 2016
cell2mat( arrayfun(@(c) c.x(2,:), (1:length(s)).', 'Uniform', 0) )
  8 Comments
Stephen23
Stephen23 on 31 Oct 2017
@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:

Sign in to comment.


Jan
Jan on 18 Feb 2016
Edited: Jan on 18 Feb 2016
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 Comment
Jack
Jack on 18 Feb 2016
I see. Braces would seem intuitive: would be nice to have such functionality in the future if possible...

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!