Does this variable exist

5 次查看(过去 30 天)
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!

采纳的回答

Stephen23
Stephen23 2020-8-31
编辑:Stephen23 2020-8-31
  2 个评论
Steven Lord
Steven Lord 2020-8-31
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 2020-9-1
Thank you for your help! I used isprop and it worked.

请先登录,再进行评论。

更多回答(1 个)

Peter O
Peter O 2020-8-31
编辑:Peter O 2020-8-31
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by