isfield和isKey是如何使用的
好问题,这两个函数在 MATLAB 里经常一起出现,但用途对象不同:
核心区别
isfield:检查 结构体 (struct) 里有没有某个字段isKey:检查 键值容器(如containers.Map,或新版本dictionary)里有没有某个键
isfield 怎么用(用于 struct)
s = struct('name', 'Alice', 'age', 20);
tf1 = isfield(s, 'name'); % true
tf2 = isfield(s, 'score'); % false也可以一次检查多个字段:
tf = isfield(s, {'name','score'});
% 返回逻辑数组 [1 0]常见场景:访问前先判断,避免报错
if isfield(cfg, 'markerCode')
code = cfg.markerCode;
else
code = -1;
endisKey 怎么用(用于 Map / dictionary)
1) containers.Map
m = containers.Map({'A','B'}, [10, 20]);
tf1 = isKey(m, 'A'); % true
tf2 = isKey(m, 'C'); % false多个键:
tf = isKey(m, {'A','C'});
% 返回 [1 0]2) dictionary(新版本 MATLAB)
d = dictionary(["A","B"], [10,20]);
tf = isKey(d, "A"); % true一句话记忆法
- 点号访问的(
s.field) → 用isfield - 键查找的(
map(key)) → 用isKey