Assigning 0 if a variable is not present in mat file

4 ビュー (過去 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
variables(pr)=zeros(1,100);
end
end
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);
end
Now extract everything from data
  5 件のコメント
Walter Roberson
Walter Roberson 2019 年 12 月 24 日
The vertcat() is not doing anything useful for you. You are only passing in a single parameter, and a parameter concatenated with nothing is the same as the parameter.
assignin('base') is recommended against; it has most of the same problems that using global has.
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by