0

I have a 10 x 10 struct with four fields a,b,c,d.

How do I convert this struct to a 10 x 10 matrix with entries only from the field a?

Suever
  • 64,497
  • 14
  • 82
  • 101
Kenneth.K
  • 135
  • 5

2 Answers2

1

You can rely on the fact that str.a returns a comma-separated list. We can therefore concatenate the values together and reshape the resulting array to be the same size as the input struct.

% If a contains scalars
out = reshape([str.a], size(str));

% If a contains matrices
out = reshape({str.a}, size(str));
Suever
  • 64,497
  • 14
  • 82
  • 101
0

One liner solution

res = cellfun(@(strctObj) strctObj.a,str,'UniformOutput',false);

Further explanation

Define a one-line function which extract the a value.

getAFunc = @(strctObj) strctObj.a;

use MATLAB's cellfun function to apply it on your cell and extract the matrix:

res = cellfun(@(strctObj) getAFunc ,strctCellObj,'UniformOutput',false);

Example

%initializes input
N=10;
str = cell(N,N);
for t=1:N*N
  str{t}.a = rand; 
  str{t}.b = rand; 
  str{t}.c = rand; 
  str{t}.d = rand; 
end
%extracts output matrix
res = cellfun(@(strctObj) strctObj.a,str,'UniformOutput',false);
ibezito
  • 5,782
  • 2
  • 22
  • 46