Enumeration class input modification possible?

2 ビュー (過去 30 日間)
Kristian Dimitrov
Kristian Dimitrov 2025 年 1 月 27 日
コメント済み: Kristian Dimitrov 2025 年 1 月 28 日
Hello fellow Matlab users.
I am having a simple enumeration class to hold some predifinded allowed values as shown below
class (Sealed = true) myMode
enumeration
CLRWRITE
MAXHOLD
MINHOLD
AVERAGE
VIEW
BLANK
end
end
I am reading a file where the above values are writen with special characters or spaces for example "CLR/WRITE" or "Max Hold". So far i am just using regexprep externally to properly format the string before enumeration.
val = "CLR/WRITE";
val = regexprep(val, '[\W]', '');
mode = myMode(val);
Unrecognized function or variable 'myMode'.
I also implemented a static method "fromString" in the class that implements the regexprep code above. But still fills clunky.
myTrace.fromString("CLR/WRITE")
methods (Static = true)
function out = fromString(val)
val = convertCharsToStrings(val{:});
if isstring(val)
val = regexprep(val, '[\W]', '');
out = myMode(val);
end
end
end
I am curious if there is a way for the enumeration class to direclty accept "CLR/WRITE" as an input. Without access to a constructor, it seems imposible to implement, but I am open to suggestions. Supperclass definition maybe?
  2 件のコメント
Matt J
Matt J 2025 年 1 月 27 日
編集済み: Matt J 2025 年 1 月 27 日
what does "directly accept" mean? What would the syntax you are after look like?
Kristian Dimitrov
Kristian Dimitrov 2025 年 1 月 28 日
I am just wandering if there is a way to make myMode("CLR/WRITE") work. Considering that the enumeration value is CLRWRITE and due to the special character in the string matlab returns error 'CLR/WRITE' is not a member of enumeration 'myMode'.

サインインしてコメントする。

回答 (1 件)

Dirk Engel
Dirk Engel 2025 年 1 月 27 日
A static method is the correct approach from an OOP perspective. In other programming languages, a static method for creating an object from a string is usally called "parse", but "fromString" is fine, too.
  1 件のコメント
Kristian Dimitrov
Kristian Dimitrov 2025 年 1 月 28 日
That is what I was thinking as well. No sneaky way arround the problem :(. Thank you for the comment!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by