简体   繁体   English

如果加载的文件中不存在变量,则将其赋值为零(八度)

[英]Assigning a variable with zero value if not existing in loaded file (Octave)

The Case1.Mat file contains XYZ 2 6 3 3 7 4 4 8 6 Case1.Mat文件包含XYZ 2 6 3 3 7 4 4 8 6

5 9 8 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. 我刚刚显示了简化问题的示例,但是在我的情况下,Mat文件包含> 300个变量,并且每种情况下变量的数量都会变化。 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. 在上面的示例中,变量'V'不在.mat文件中,因此会导致错误并停止执行。 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. 我的问题是,每当遇到以下情况时,'labels'中定义的变量不在已加载的.Mat文件中,则该变量值(在这种情况下为'V')应分配为零(双精度),这样我的Nrow应该是'4',而我的'ResMat'应该看起来像这样ResMat = [5; 9; 8; 0]我是这个编程环境的新手,请原谅我提出问题的方式。

After reply 回复后
Case1_lg.MAT error: 'oflv3' undefined near line 8 column 33 Case1_lg.MAT错误:在第8行第33列附近未定义'oflv3'

error: called from procsMax3 at line 8 column 6 错误:从procsMax3在第8行第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 在上述情况下,lv3不在.Mat文件中

You can use exist to check for the existence of a variable and if that variable isn't defined, assign a default value 您可以使用exist检查变量是否存在,如果未定义该变量,则分配一个默认值

if ~exist('V', 'var')
    V = 0;
end

A better approach though is to specify an output to load so that all variables are assigned as fields in a struct 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. 不过,更好的方法是指定要load的输出,以便将所有变量都分配为struct字段,因此您不必担心会覆盖已经存在于用户工作空间中的变量或其他许多可能的问题。 In this case, you could use isfield to check if V is present in the file and replace with a default value if needed 在这种情况下,可以使用isfield检查文件中是否存在V并在需要时替换为默认值

data = load(filename);

if ~isfield(data, 'V')
    data.V = 0;
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM