The Case1.Mat file contains X Y Z 2 6 3 3 7 4 4 8 6
5 9 8
load(Case1.Mat); # loaded a Case1.Mat file in Octave
label=[{X;Y;Z;V}]; # I have a matrix of predefined variables
Nrow=numel(label);
ResMat=ones(Nrow,1);
for k=1:Nrow;
ResMat(k,1)=max(label{k,1});
End
I have just shown the example of simplification of my problem, however in my case the Mat file contains >300 Variables, and for each case the number of variables changes. Hence I have defined a label matrix with all the variables. In the above example the variable ‘V’ is not in the .mat file and hence it results in an error and execution stops. I am trying to compute the maximum of each variable(column). My question is, whenever, I encounter a situation where, the defined variable in ‘labels’ is not in the loaded .Mat file then that variable value (‘V’ in this case) should be assigned as zero (double) so that my Nrow should be ‘4’ and my ‘ResMat’ should look like this ResMat=[5;9;8;0] I am new to this programming environment so pardon the way I have put the question.
After reply
Case1_lg.MAT
error: 'oflv3' undefined near line 8 column 33
error: called from procsMax3 at line 8 column 6
# Constantes (my actual code)
for i=1;
for j={'lg'};
filename = strcat("Case",sprintf("%d",i),"_",j{},".MAT");
load(filename);
display(filename);
Ncol=1;
label=[{vBrfrda;vBrfrdb;vBrfrdc;oflv3}];
if ~isfield(label, 'V')
data.V = 0;
endif
Nrow=numel(label);
ResMat=ones(Nrow,Ncol);
for k=1:Nrow;
ResMat(k,i)=max(label{k,i});
end
end
end
in the above case oflv3 is not in the .Mat file
You can use
exist
to check for the existence of a variable and if that variable isn't defined, assign a default valueA better approach though is to specify an output to
load
so that all variables are assigned as fields in astruct
so you don't have to worry about overwriting variables that may be in the user's workspace already or a host of other possible issues. In this case, you could useisfield
to check ifV
is present in the file and replace with a default value if needed