From: Jan Simon on
Dear Jay,

> I modified a bit. Now I initiated the field first and would like to concatenate two structs into one struct, but still failed.
>
> Could you explain why?

You repeat the same error again. As posted already several times, you cannot asign an element of a struct array with a struct which has different fields. Even a different order is impossible.

Please test this with some smaller test structs. Using lower case characters for the names of the variables helps sometimes to reduce the optical confusion.

A(1) = struct('a', 1, 'b', 2);
A(2) = struct('b', 3, 'a', 4); % Error: dissimilar structures...

B(2) = struct('a', 1, 'b', 2);
B(1) = struct('a', 3, 'b', 4); % Ok

C(1) = struct('a', 1, 'b', 2);
C(2) = struct('a', 3, 'b', 4, 'c', 5); % Error: dissimilar structures

Is it getting clearer?

Jan
From: Emil on
I am also having problems dealing with arrays of structures, even though they are slightly different.

Given an structure that among others has a substructure sub1. In sub1.matrix there is a matrix I would like to base other fields on.

Namely I want to initialize another substructure, with only one initial field containing a column vector. Code would be

for i = 1:numel(struct)
struct(i).sub2.vector = true(size(struct(i).sub1.matrix,1),1);
end

The structure is rather big and this loop takes very long, can this be optimized somehow? Thanks a lot
From: Oleg Komarov on
"Emil " <emil4ml(a)gmail.com> wrote in message <i2rd3b$n72$1(a)fred.mathworks.com>...
> I am also having problems dealing with arrays of structures, even though they are slightly different.
>
> Given an structure that among others has a substructure sub1. In sub1.matrix there is a matrix I would like to base other fields on.
>
> Namely I want to initialize another substructure, with only one initial field containing a column vector. Code would be
>
> for i = 1:numel(struct)
> struct(i).sub2.vector = true(size(struct(i).sub1.matrix,1),1);
> end
>
> The structure is rather big and this loop takes very long, can this be optimized somehow? Thanks a lot

First of all don't name your struct since "struct" is a matlab function (which creates structures).

Second i suggest you to create your struct which henceforward I will call "s" as:
s.sub1(ii).matrix
insterad of:
s(ii).sub1.matrix

Using the first syntax:

% Create example structure
clear s
for f = 1:1000
n = ceil(rand(1)*100);
s.sub1(f).matrix = rand(n);
end

% Add sub2
tic
s.sub2 = cell2struct(arrayfun(@true,cellfun('size',{s.sub1.matrix},1),ones(1,numel({s.sub1.matrix})),'un',0).','vector',2).';
toc
0.004796 seconds.

Oleg