Does this variable exist

4 visualizaciones (últimos 30 días)
Andrea Daou
Andrea Daou el 31 de Ag. de 2020
Comentada: Andrea Daou el 1 de Sept. de 2020
Hello,
Is it possible to check if a sub variable of a variable existing in the workspace exists?
For exemple 'layers' variables exist in the workspace, how can I put a condition on the existance of layers(k).Weights ?
I know that exist('layers','var') is used to check the existance of variables in workspace.
Thank you! Appreciate any help!

Respuesta aceptada

Stephen23
Stephen23 el 31 de Ag. de 2020
Editada: Stephen23 el 31 de Ag. de 2020
  2 comentarios
Steven Lord
Steven Lord el 31 de Ag. de 2020
For objects see isprop to determine if the property exists. This is particularly useful for classes with dynamic properties. As an example, define a class:
classdef sometimesX < dynamicprops
methods
function obj = addpropX(obj, xval)
addprop(obj, 'X');
obj.X = xval;
end
end
end
and use that class:
>> y = sometimesX
y =
sometimesX with no properties.
>> isprop(y, 'X')
ans =
logical
0
>> y = addpropX(y, 42)
y =
sometimesX with properties:
X: 42
>> isprop(y, 'X')
ans =
logical
1
Andrea Daou
Andrea Daou el 1 de Sept. de 2020
Thank you for your help! I used isprop and it worked.

Iniciar sesión para comentar.

Más respuestas (1)

Peter O
Peter O el 31 de Ag. de 2020
Editada: Peter O el 31 de Ag. de 2020
For structures, use isfield()
clear a
a.M = 'hat';
isfield(a,'M') % True
isfield(a,'N') % False
For array size, use length(a) to find the longest dimension of a, or size(a,d) to find the length of the dth dimension (1=row, 2=col, 3=page, 4... etc). To get the total number of elements, use numel(x). Above you are using a struct array. For your use case:
if numel(layers) < k || ~isfield(layers,'Weights')
% handle undersize struct and/or missing field here
end

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by