MATLAB Answers

Assigning 0 if a variable is not present in mat file

5 ビュー (過去 30 日間)
adi kul
adi kul 2019 年 12 月 24 日
コメント済み: Walter Roberson 2019 年 12 月 24 日
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?

回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 12 月 24 日
if ~isfield(data, variables{pr})
data.(variables{pr}) = zeros(1,100);
Now extract everything from data
  5 件のコメント
Walter Roberson
Walter Roberson 2019 年 12 月 24 日
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.



Community Treasure Hunt

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

Start Hunting!

Translated by