Assigning 0 if a variable is not present in mat file
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
Antworten (1)
Walter Roberson
am 24 Dez. 2019
if ~isfield(data, variables{pr})
data.(variables{pr}) = zeros(1,100);
end
Now extract everything from data
5 Kommentare
Walter Roberson
am 24 Dez. 2019
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
am 24 Dez. 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.
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!