assign the content of a structure to another
Show older comments
I have two structures A and B having the same fields but not the same sizes. The size of A can be bigger or smaller than B depending on the code. A is originally defined and I want to change its content at the end of the round to use what is in B. So what I want to do is to assign the content of B to A and if there are more fields in A , remove them. If there is less add the missing ones.
I tried
[A]= B;
It does not give me any error but the result I get is not correct. Then I tried something like
[A(1:numel(B)).field1]=B.field1;
...
[A(1:numel(B)).fieldn]=B.fieldn;
but I get an error because both structures do not have the same number of elements.
I tried also
[A(1:length(B)).field1]=B.field1;
No errors but the result is not correct either. What is the right way to it? And why the first one does not work?
Accepted Answer
More Answers (1)
Guillaume
on 1 Feb 2016
There's something that you're not explaining correctly. "I want to change its content at the end of the round to use what is in B" to me reads as if you simply want to assign B to A, in which case:
A = B; %no need for the [] which doesn't do anything
So, when you say "the result is not correct", in what way is it not correct?
Note that with the above, it does not matter what is originally in A. A could be a structure with whichever size and whatever fields, it could be a matrix, or even not exist. By saying A = B you're essentially creating a new A which has nothing to do with the old one (if it existed).
Now, when you say that
[A(1:numel(B)).field1]=B.field1
gives you "an error because both structures do not have the same number of elements", that shouldn't be the case. Is that the exact command that you entered? It does not give an error for me. If A is smaller than B, it'll be automatically resized to fit the size of B. If A is larger than B, only the first b elements of A will be replaced, where b = numel(B).
Finally, your last instruction (with length) is the same as
[A(1:numel(B)).field1]=B.field1
if B is a vector. If B is a matrix, then it will only copy the first x elements of B where x is the length of the largest dimension of B. Surely not what you want in any case. As a rule avoid length or learn what it means (as per doc length(m) = max(size(m)))
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!