Does this variable exist

4 ビュー (過去 30 日間)
Andrea Daou
Andrea Daou 2020 年 8 月 31 日
コメント済み: Andrea Daou 2020 年 9 月 1 日
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 Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by