Does this variable exist

5 vues (au cours des 30 derniers jours)
Andrea Daou
Andrea Daou le 31 Août 2020
Commenté : Andrea Daou le 1 Sep 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!

Réponse acceptée

Stephen23
Stephen23 le 31 Août 2020
Modifié(e) : Stephen23 le 31 Août 2020
  2 commentaires
Steven Lord
Steven Lord le 31 Août 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 le 1 Sep 2020
Thank you for your help! I used isprop and it worked.

Connectez-vous pour commenter.

Plus de réponses (1)

Peter O
Peter O le 31 Août 2020
Modifié(e) : Peter O le 31 Août 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

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by