Kenneth.K
Kenneth.K

Reputation: 135

How to convert a struct to a matrix

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?

Upvotes: 0

Views: 765

Answers (2)

Suever
Suever

Reputation: 65430

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));

Upvotes: 1

ibezito
ibezito

Reputation: 5822

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);

Upvotes: 0

Related Questions