Вы можете использовать структуру данных, похожую на ассоциативный массив, с точным именем struct()
.
% Create a new struct
trigrams = struct();
% Add an item explicitly, by using the format 'struct.key',
% where 'key' can be an arbitrary key
trigrams.length = 0;
trigrams.thr = 0.02;
trigrams.length += 1;
% Use setfield() when you don't know the key beforehand (e.g. if you're reading
% the values from a file, etc.)
trigramkey = 'hi';
trigrams = setfield(trigrams, trigramkey, 0.0007);
trigrams.length += 1;
% Likewise, use getfield() when you need a value dynamically
workingprob = getfield(trigrams, trigramkey);
% You can also check the existence of a key
hi_exists = isfield(trigrams, 'hi');
% By the way, you don't actually have to track the length like I've been doing
trigramlength = length(fieldnames(trigrams));
Обратите внимание, что функция setfield()
не на месте;он возвращает новую структуру.