subtract values from fields of two different structs

4 views (last 30 days)
Dear matlab-experts! My .mat-file is a 2x1 cell that contains 2 structs. Each struct contains two fields: 1 is called ‘number’, the other ‘length’. One struct has 3 inputs, the other 4.
My objective: I want to scan both structs for numbers that have the same value, then take the associated lengths and subtract them. If one number only appears in one struct (eg. number 4 exists only in struct 2) nothing shall be calculated. I'm sorry, I really don't have any idea how to do this :(
It should be sth like below:
For example{1}.number==example{2}.number
difflength= example{2}.length-example{1}.length
end
attached I send the example.mat file Thank u so much for any suggestions how I can solve my problem!!
  1 Comment
Adam
Adam on 8 May 2015
What do you mean by 'One struct has 3 inputs, the other 4'? A struct doesn't have inputs as such.

Sign in to comment.

Answers (2)

Guillaume
Guillaume on 8 May 2015
Use ismember (or maybe intersect to find the number common to both arrays. Note that the fact you have structure is pretty much irrelevant here.
[iscommon, posinstruct2] = ismember(example{1}.number, example{2}.number);
%iscommon is true if the element in example{1}.number is found in example{2}.number
%posinstruct2 is the index in struct2 of the corresponding element in struct1
lengthdiff = example{2}.length(posinstruct2(iscommon)) - example{1}.length(iscommon)
%this return the length difference, in the order of the numbers in struct1, only for those
%numbers that are common to both

Magdalena
Magdalena on 21 May 2015
sorry for the late reply, but thanks a lot for the answer, it did help me a lot!!

Categories

Find more on Structures 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!