3
votes

I have a struct called A which has a [1x1] struct called B, and when I run A.B in the command line, it returns two types of answers:

ans = 
    X: 3
    Y: 2
    Z: 4

ans = 
    X: 1
    Y: 5
    Z: 9
    W: 4
    V: 2

EDIT: What I'm trying to do is put all the values of X into a vector, so that the vector would look something like this: [3, 1, ...]

To do so, I'm first creating a vector called AB so that I can put [AB.X] into a another vector that I can use.

My current strategy is running a for loop like this one:

for idx = 1:length(A)
    AB(idx) = [A(idx).B];
end

But I get an error, "Subscripted assignment between dissimilar structures." I think that's because some values of B have 3 parts while others have 5.

How can I resolve this?

Or is there a way better than using a for loop?

1
What exactly are you trying to put into another vector? Do you want the values of each field in your struct? You are getting that when doing A.B because A is a two element struct. The first struct element has three fields while the other element has five. By doing A.B you are unpacking all of the structs and it has nowhere else to go, so it floods the command prompt with each struct. - rayryeng
@rayryeng - I want something like this: AB(1) = A(1).B which would give X: 2, Y: 4, Z: 2, etc etc I also made edits in my original question - Dan

1 Answers

1
votes

The structs can't be concatenated together with different fields. One thing you can do to get to X is place all the struct elements into a cell array and then call cellfun to dereference X:

 ABX = cellfun(@(c) c.X, {A.B}) 

Resources:

Comma separated lists

cellfun

Anonymous functions