Does this variable exist

5 views (last 30 days)
Andrea Daou
Andrea Daou on 31 Aug 2020
Commented: Andrea Daou on 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!

Accepted Answer

Stephen23
Stephen23 on 31 Aug 2020
Edited: Stephen23 on 31 Aug 2020
  2 Comments
Steven Lord
Steven Lord on 31 Aug 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 on 1 Sep 2020
Thank you for your help! I used isprop and it worked.

Sign in to comment.

More Answers (1)

Peter O
Peter O on 31 Aug 2020
Edited: Peter O on 31 Aug 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

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!