Assigning 0 if a variable is not present in mat file

3 views (last 30 days)
adi kul
adi kul on 24 Dec 2019
Commented: Walter Roberson on 24 Dec 2019
I am trying to assign zero to a variable which is not available in mat file. I am trying to make it work with following code which is not working as per my logic.
variables= {'abc','def','ghi','jkl','mno'};
data= load('xyz.mat')
for pr=1:numel(variables)
if isfield(data, variables(pr))==0
I am not able to make it work like I want to. So basically what I am trying to do is if suppose variable abc is not there in xyz.mat, I want to create abc of zeros(1,100) and if def is there in xyz.mat then I want to use it as it is.
Is this possible in matlab?

Answers (1)

Walter Roberson
Walter Roberson on 24 Dec 2019
if ~isfield(data, variables{pr})
data.(variables{pr}) = zeros(1,100);
Now extract everything from data
Walter Roberson
Walter Roberson on 24 Dec 2019
I did recognize a difficulty with the
data = [data{:}];
at the time I posted it. The loop checking for those variables ensures that at least those variables are present, but it does not do anything about the possibility that additional variables are present in a file. The concatenation of structures that I do can only work if all of the struct have the same fields in the same order; the orderfields() call imposes a consistent order of the fields that are present, but the logic I posted does not protect against the possibility that some file has extra fields; your problem statement does not define what the result should be in that case.

Sign in to comment.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!